skip to Main Content

In my React app, when you refresh the browser I have to update 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

Answers


  1. 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).

    Login or Signup to reply.
  2. 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 isLocalStorageAvailable = typeof window !== "undefined" && window.localStorage;
      
        return isLocalStorageAvailable
          ? Number(window.localStorage.getItem("count")) || 0
          : 0;
      }
    
      const increment = () => setCount((prev) => prev + 1);
      const decrement = () => setCount((prev) => prev - 1);
    
      useEffect(() => {
        window.localStorage.setItem("count", String(count));
      }, [count]);
    
      return (
        <>
          <h1>Hello World!</h1>
          <p>Count: {count}</p>
          <button onClick={increment}>+</button>
          <button onClick={decrement}>-</button>
        </>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search