Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Last active September 18, 2021 05:30
Show Gist options
  • Save danieljpgo/9dfa091a3a1cb7185cb04e1d2e2f168e to your computer and use it in GitHub Desktop.
Save danieljpgo/9dfa091a3a1cb7185cb04e1d2e2f168e to your computer and use it in GitHub Desktop.
export function useLocalStorageReducer<Data extends React.Reducer<any, any>>(
key: string,
reducer: Data,
initialState: React.ReducerState<Data>,
{ serialize = JSON.stringify, deserialize = JSON.parse } = {},
) {
const [state, dispatch] = React.useReducer(reducer, initialState, () => {
const init = typeof initialState === 'function' ? initialState() : initialState;
try {
const valueInLocalStorage = window.localStorage.getItem(key);
return valueInLocalStorage ? deserialize(valueInLocalStorage) : init;
} catch (error) {
return init;
}
});
const prevKeyRef = React.useRef(key);
React.useEffect(() => {
const prevKey = prevKeyRef.current;
if (prevKey !== key) {
window.localStorage.removeItem(prevKey);
}
prevKeyRef.current = key;
window.localStorage.setItem(key, serialize(state));
}, [key, state, serialize]);
return [state, dispatch] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment