React Answers

How to persist state on refresh with React?

Spread the love

To persist state on refresh with React, we use local storage.

For instance, we write

const Counter = () => {
  const [count, setCount] = useState(1);

  useEffect(() => {
  }, []);

  useEffect(() => {
    window.sessionStorage.setItem("count", count);
  }, [count]);

  return (
    <div className="App">
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.