reactive localstorage in react
snippet in javascript

reactive localstorage in react

user1063


function useStorageWatcher(key) {
  const [val, setVal] = useState(localStorage.get(key));

  useEffect(() => {
    const handler = () => val !== localStorage.get(key) && setVal(localStorage.get(key));
    window.addEventListener("storage", handle);
    () => window.removeEventListener("storage", handler);
  }, []);

  useEffect(() => {
    setVal(localStorage.get(key));
  }, [key]);

  return val;

}