how to persist usestate value in localstorage in javascript

To persist the state value of a useState hook in localStorage in JavaScript, you can use the useEffect hook to set the localStorage value when the component mounts and update the state value whenever the localStorage value changes. Here's an example:

import { useState, useEffect } from 'react';

function App() {
  const [count, setCount] = useState(() => {
    const initialValue = Number(window.localStorage.getItem('count'));
    return initialValue || 0;
  });

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

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

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

export default App;
530 chars
26 lines

In this example, we store the count value in localStorage when the component mounts and update the count value whenever the localStorage value changes. To set the initial value of count, we use a callback function in the useState hook that retrieves the localStorage value, parses it to a number using Number(), and returns it. If there is no localStorage value, we set the initial value to 0.

Note that you should always use the localStorage API inside useEffect hook to avoid issues with server-side rendering.

gistlibby LogSnag