DEV Community

Discussion on: Storing State on Local Storage in a React Application

Collapse
 
link2twenty profile image
Andrew Bone

I made a hook for making this sort of thing easier.

You would just need to do something like.

const [state, setState] = useState();

useEffect(() => {
  const setHandler = (key) => {
    if(key === "state") setState(storage.get("state"));
  }

  storage.on('set', setHandler);

  return () => {
    storage.off('set', setHandler);
  }
})
Enter fullscreen mode Exit fullscreen mode

Which will mean, provided you use the storage context, the state will always be in sync with local/session storage.