Skip to content

Instantly share code, notes, and snippets.

@Nurou
Created February 28, 2022 17:44
Show Gist options
  • Save Nurou/f605f581f82d8dd2642eec96f715a7f4 to your computer and use it in GitHub Desktop.
Save Nurou/f605f581f82d8dd2642eec96f715a7f4 to your computer and use it in GitHub Desktop.
useReducerWithLocalStorage
// 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