Answers for "reactive localstorage in react"

1

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;

}
Posted by: Guest on August-12-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language