usePersistentState Hook

DEMO
You have visited this page 0 time
This is a custom hook that saves the state into local storage when initialised/updated, and retrieves it in future sessions.
Demo.jsx

usePersistentState.jsx
const Demo = () => {
  const [numVisits, setVisits] = usePersistentState(0, "numVisits");

  useEffect(() => {
    setVisits((numVisits) => parseInt(numVisits) + 1);
  }, [setVisits]);

  return (
    <div>
      <span>You have visited this page </span>
      <strong onClick={() => setVisits(numVisits + 1)}>{numVisits}</strong>
      <span> time{numVisits > 1 && "s"}</span>
    </div>
  );
};
export default Demo;

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React