skip to Main Content

In my React app I set my localStorage item count with a value of 1.

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

How do I increment this localStorage value by 1, on every page refresh?

2

Answers


  1. Before setting the value in localStorage, check if value already exists and increment if exists otherwise set to 1.

    useEffect(() => {
        let val = window.localStorage.getItem('count');
        val = val ? parseInt(val) : 0
        window.localStorage.setItem('count', String(val + 1));
    }, []);
    

    Ref – https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

    Login or Signup to reply.
  2. To increment the value of the count item in localStorage; you can use the following code inside your useEffect:

    useEffect(() => {
      const currentCount = Number(window.localStorage.getItem('count')) || 0;
      window.localStorage.setItem('count', String(currentCount + 1));
    }, []);
    

    CODE SAMPLE


    NOTE:

    You can also notice that page refresh count is incremented by 2 in development because of new React18 feature1.

    Docs Reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search