how to persist usestate value in javascript

In order to persist the value of a useState hook in JavaScript, you can make use of the localStorage API.

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

function App() {
  const [count, setCount] = useState(() =>
    JSON.parse(localStorage.getItem("count")) || 0
  );

  useEffect(() => {
    localStorage.setItem("count", JSON.stringify(count));
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount((prevCount) => prevCount + 1)}>
        Increment
      </button>
      <button onClick={() => setCount((prevCount) => prevCount - 1)}>
        Decrement
      </button>
    </div>
  );
}
539 chars
24 lines

In this example, we initialize the count state with an IIFE that retrieves the value from localStorage, or defaults to 0 if there is no value. Whenever the count state updates, we store the new value in localStorage using the useEffect hook with count as a dependency.

gistlibby LogSnag