Skip to content

Instantly share code, notes, and snippets.

@Liroo
Last active January 22, 2020 09:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Liroo/ae5a4fb3b8cd7706aa0283db6f9c7104 to your computer and use it in GitHub Desktop.
Save Liroo/ae5a4fb3b8cd7706aa0283db6f9c7104 to your computer and use it in GitHub Desktop.
Really simple react hook for persistant reducer across session.
import { useReducer } from 'react';
export const usePersistReducer = (reducer, initialState, key) => {
let persistKey = `__PERSIST_REDUCER_${key}__`
const persistReducer = (state, action) => {
let newState = reducer(state, action);
localStorage.setItem(persistKey, JSON.stringify(newState));
return newState;
}
let persistInitialState = localStorage.getItem(persistKey);
if (!persistInitialState) {
persistInitialState = initialState;
} else {
try {
persistInitialState = JSON.parse(persistInitialState);
} catch (err) {
persistInitialState = initialState;
}
}
return useReducer(persistReducer, persistInitialState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment