How to increment local storage item value by 1 when refreshing the browser in React app

73 Views Asked by At

In my React app, when you refresh the browser I have to update / increment the count value by 1. Also I want to store this count in localStorage.

How do I manage this?

As a start I have something like this:

 const initialCount = () => {
  if (typeof window !== 'undefined' && hasRedirectQueryParam) {
   return Number(window.localStorage.getItem('count')) || 0;
  }
   return null;
  };

 const [count, setCount] = useState(initialCount);

 useEffect(() => {
   setCount(count);
   window.localStorage.setItem('count', String(initialCount()));
  }, []);

But how do I use setCount now? So when the browser refresh count increments by 1?

What is a proper React implementation for this using React useState and useEffect hooks?

2

There are 2 best solutions below

0
On

you should not use react state. just read the count from local stroage and update the value whenever the app launches (for example inside app.js file but outside the component).

0
On

I think this is what you want. You can define the initialCount function as shown below so that it can be hoisted. You should add the number in the dependency array so that the newest value will be persisted in the local storage.


const App = () => {
  const [count, setCount] = useState(initialCount);

  function initialCount() {
    const count = window.localStorage.getItem("count");
    return count ? Number(count) : 0;
  }

  useEffect(() => {
    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  function handleBeforeUnload() {
    setCount((prev) => {
      const count = prev + 1;
      window.localStorage.setItem("count", String(count));
      return count;
    });
  }
  
  return (
    <>
      <h1>Hello World!</h1>
      <p>Count: {count}</p>
    </>
  );
};

export default App;