DEV Community

Cover image for Quick Example on using LocalStorage in React
Clarence Onumajulu
Clarence Onumajulu

Posted on

Quick Example on using LocalStorage in React

In this example, I would quickly show you how to store the state of an item in React with LocalStorage.

Usage in Vanilla vs. React

The difference between using localStorage in React compared to Vanilla javascript is that we have to make use of two React hooks.
I would assume you already know what these are but if you don't you can visit these links below.
useState
useEffect

Example

I am trying to toggle the state of an item between 'On' and 'Off' and want to store that state in the browser. Here's how I would go about it.

<button onClick={() => changeOn(!isOn)}>
Enter fullscreen mode Exit fullscreen mode
const [isOn, setisOn] = useState(localStorage.getItem('Status') === 'true');

useEffect(()=> {
    localStorage.setItem('Status', JSON.stringify(isOn));
}, [isOn])

function changeOn(status){
    setisOn(status);
}
Enter fullscreen mode Exit fullscreen mode

That's it!
If you're still confused I would be happy to explain my solution to you in the comments.

Goodluck!

Top comments (0)