React Hook: useLocalStorage

 by Robin Wieruch
 - Edit this Post

A neat that shows how to use local storage in React to store state. You can just use it in any React component and it allows you to write and read state to and from the local storage:

import * as React from 'react';
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];
};
const App = () => {
const [isOpen, setOpen] = useLocalStorage('is-open', false);
const handleToggle = () => {
setOpen(!isOpen);
};
return (
<div>
<button onClick={handleToggle}>Toggle</button>
{isOpen && <div>Content</div>}
</div>
);
};
export default App;

The local storage hook is only there as a learning experience though. If you rely on the local storage for your React application in production, you should check out more widely used hooks (and therefore robust) hooks which are maintained as an open source library. For example, for the local storage I personally always fall back to this local storage hook.

Keep reading about 

React introduced Hooks quite a while ago. With their release, Hooks gave function components the ability to use state and side-effects with built-in Hooks such as React's useState Hook and…

In this React tutorial, you will learn how to store state in local storage by using a custom React Hook . We will address the session storage shortly as well, but essentially it is used the same…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.