Skip to content

Instantly share code, notes, and snippets.

@JohanAltamar
Last active September 22, 2020 04:50
Show Gist options
  • Save JohanAltamar/6be4656a3b1eea0755ed9b43af8c4108 to your computer and use it in GitHub Desktop.
Save JohanAltamar/6be4656a3b1eea0755ed9b43af8c4108 to your computer and use it in GitHub Desktop.
Persist react hooks state at LocalStorage
import { useEffect, useState } from 'react';
export function usePersistedState(key, defaultValue) {
const [state, setState] = useState(
() => JSON.parse(localStorage.getItem(key)) || defaultValue
);
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment