To persist state on refresh with React, we use local storage.
For instance, we write
const Counter = () => {
const [count, setCount] = useState(1);
useEffect(() => {
setCount(JSON.parse(window.sessionStorage.getItem("count")));
}, []);
useEffect(() => {
window.sessionStorage.setItem("count", count);
}, [count]);
return (
<div className="App">
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
};
to define the Counter
component.
In it, we call setCount
in the first useEffect
callback to get the local storage item with key 'count'
with getItem
.
And we call setCount
to set the count
state with the returned value.
We call useEffect
with an empty array to load the value on component mount.
Then we call useEffect
again to watch the count
value.
We call setItem
to set the item with key 'count'
to the current count
value.
Then we add a button that calls setCount
to update the count
.