Save a value in persistent storage with useReducer
- Estimated read time: 1 minReact doesn’t provide a hook to store state in persistent storage such as localStorage
. For a simple state, we can adopt the useLocalStorage provided by the usehooks website. It wraps the useState
hook.
However, how about a complicated object? It would be better to wrap the useReducer
hook. Here is my implementation. The dataProvider
is an abstraction of the persistent storage. For example, if we want to use localStorage
, then just replace it with the APIs of localStorage
.