Persistent State Hooks. Combines the syntax and APIs of `useState` and `useReducer` with localStorage and sessionStorage to make state persistence easy and clean.
npm install react-use-persistPersistent State Hooks. Combines the syntax and APIs of useState and useReducer with localStorage and sessionStorage to make state persistence easy and clean.
- useLocalState | useSessionState
``typescript`
// localStorage
const [state, setState, remove] = useLocalState(key, initialState, { writeInit });
// sessionStorage
const [state, setState, remove] = useSessionState(key, initialState, { writeInit });
##### Options:
- key: stringinitialState
- Required
- Storage unique identifier
- : anywriteInit
- Optional initial value
-
- By default, state does not persist on initialization. However, if for some reason this is needed, simply mark this true.
- useLocalReducer | useSessonReducer
`typescript`
// localStorage
const [state, dispatch, remove] = useLocalReducer(key, reducer, initialState, { writeInit });
// sessionStorage
const [state, dispatch, remove] = useSessionReducer(key, reducer, initialState, { writeInit });
##### Options:
- key: string reducer
- Required
- Storage unique identifier
- initialState
- Required
- Any reducer function
- : anywriteInit
- Optional initial value
-
- By default, state does not persist on initialization. However, if for some reason this is needed, simply mark this true.
##### Returns:
- [state, setStateOrDispatch, remove]useState
- The first two arguments will be identical to those returned by React's and useReducer hooks.remove
- A third argument is provided. Calling remove` will clear the state and the key from the persistent storage.
https://codesandbox.io/s/react-use-persist-07elu?file=/src/App.js