showing results for - "reactive localstorage in react"
Willie
13 Oct 2019
1
2function useStorageWatcher(key) {
3  const [val, setVal] = useState(localStorage.get(key));
4
5  useEffect(() => {
6    const handler = () => val !== localStorage.get(key) && setVal(localStorage.get(key));
7    window.addEventListener("storage", handle);
8    () => window.removeEventListener("storage", handler);
9  }, []);
10
11  useEffect(() => {
12    setVal(localStorage.get(key));
13  }, [key]);
14
15  return val;
16
17}
18
19
20