Skip to content

Instantly share code, notes, and snippets.

@vogelino
Last active April 6, 2022 22:07
Show Gist options
  • Save vogelino/856fc5d0832392c9bfdad84711732e4a to your computer and use it in GitHub Desktop.
Save vogelino/856fc5d0832392c9bfdad84711732e4a to your computer and use it in GitHub Desktop.
React Hook: useLocalStorage

React Hook: useLocalStorage

Code by Robin Wieruch copied from his article

const useLocalStorage = (storageKey, fallbackState) => {
const [value, setValue] = React.useState(
JSON.parse(localStorage.getItem(storageKey)) || fallbackState
);
React.useEffect(() => {
localStorage.setItem(storageKey, JSON.stringify(value));
}, [value, storageKey]);
return [value, setValue];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment