Skip to content

Instantly share code, notes, and snippets.

@eoguvo
Created February 6, 2021 01:26
Show Gist options
  • Save eoguvo/d2b65443873c1bf93b3f72ce9980851a to your computer and use it in GitHub Desktop.
Save eoguvo/d2b65443873c1bf93b3f72ce9980851a to your computer and use it in GitHub Desktop.
useState with localStorage
import { useState, useEffect } from 'react';
function usePersistedState(key, initialState) {
const [state, setState] = useState(() => {
if(typeof window === 'undefined') return initialState;
const storageValue = localStorage.getItem(key);
if (storageValue) {
return JSON.parse(storageValue);
} else {
return initialState;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
}
export default usePersistedState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment