Last active
September 18, 2021 05:30
-
-
Save danieljpgo/9dfa091a3a1cb7185cb04e1d2e2f168e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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