Last active
January 22, 2020 09:47
-
-
Save Liroo/ae5a4fb3b8cd7706aa0283db6f9c7104 to your computer and use it in GitHub Desktop.
Really simple react hook for persistant reducer across session.
This file contains hidden or 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
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