Created
February 28, 2022 17:44
-
-
Save Nurou/f605f581f82d8dd2642eec96f715a7f4 to your computer and use it in GitHub Desktop.
useReducerWithLocalStorage
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
// this is a TS & modified version of: https://gist.github.com/mattiaerre/8dbd2d8efca3f242c7085a9ce82ecbde | |
import * as React from 'react'; | |
// from: https://usehooks.com/useLocalStorage | |
import { useLocalStorage } from './useLocalStorage'; | |
export const useReducerWithLocalStorage = <S, A>(reducer: React.Reducer<S, A>, initializerArg: S, key: string) => { | |
const [localStorageState, setLocalStorageState] = useLocalStorage(key, initializerArg); | |
return React.useReducer( | |
(state: S, action: A) => { | |
const newState = reducer(state, action); | |
setLocalStorageState(newState); | |
return newState; | |
}, | |
{ ...localStorageState } | |
); | |
}; | |
export default useReducerWithLocalStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment