Sometimes, we want to maintain state after a page refresh in React.
In this article, we’ll look at how to maintain state after a page refresh in React.
How to maintain state after a page refresh in React?
To maintain state after a page refresh in React, we can save the state in session storage.
For instance, we write
const Comp = () => {
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 save the latest value of count
to session storage with sessionStorage.setItem
.
We watch the value of count
and call sessionStorage.setItem
whenever it changes with the useEffect
hook.
To get the item after it refreshes, we call sessionStorage.getItem
in the first useEffect
callback, which is called with an empty array so it’s run only when the component first mounts.
Conclusion
To maintain state after a page refresh in React, we can save the state in session storage.
One reply on “How to maintain state after a page refresh in React?”
React strict mode should be turned off for this to work. Or else useState would be called twice, and changes its state back to initial state.