Save a value in persistent storage with useReducer

Save a value in persistent storage with useReducer

- Estimated read time: 1 min

React 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.


export const usePersistentStorage = (update, initialStorage, storageKey, dataProvider, init = null) => {

	const [storage, dispatch] = React.useReducer(update, initialStorage, (initialState) => {
        const persistentStorage = dataProvider.getData(storageKey);

        if (persistentStorage !== null) {
            return persistentStorage;
        } else if (init !== null) {
            return init(initialState);
        } else {
            return initialState;
        }
    });
	
	dataProvider.setData(storageKey, storage);
	return [storage, dispatch];
}
Zhe Cai

Zhe Cai

A man who is chasing dreams

comments powered by Disqus
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora