how to persist usestate value in localstorage and load on page load in javascript

To persist the value of useState in localStorage and load it on page load, we can use the useEffect hook. In this example, we will create a basic counter that will increment its value on each click and persist its value in localStorage.

Here's the code:

import React, { useState, useEffect } from 'react';

const Counter = () => {
  const [count, setCount] = useState(() => {
    const storedCount = localStorage.getItem('count');
    return storedCount !== null ? parseInt(storedCount) : 0;
  });

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

  const incrementCount = () => {
    setCount(prevCount => prevCount + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
};

export default Counter;
555 chars
26 lines

In the above code, we are using the useState hook to create a state variable count, which is initially set by reading its value from localStorage. We are parsing the value returned from localStorage as an integer using parseInt().

We are using the useEffect hook to persist the value of count in localStorage on every update. We are passing an array with count as its only element to the useEffect hook, which makes sure that the localStorage is updated only when the count value changes.

Finally, we have an incrementCount function that updates the value of count by calling the setCount function. On every update, the value of count is displayed on the screen, and we have provided a Save to LocalStorage option to store the count value in localStorage.

gistlibby LogSnag