Categories
React Answers

How to maintain state after a page refresh in React?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.