reactive localstorage in react

160

reactive localstorage in react -

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;

}


Comments

Submit
0 Comments