React Persist Context to LocalStorage - gecko-8/devwiki GitHub Wiki

Up

  1. Add a couple methods to your Context file (or anywhere and import them)
    function setLocalStorage(key, value) {
      try {
    function setLocalStorage(key, value) {
      try {
        window.localStorage.setItem(key, JSON.stringify(value));
      } catch (e) {
        // catch possible errors:
        // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
      }
    }
    
    function getLocalStorage(key, initialValue) {
      try {
        const value = window.localStorage.getItem(key);
        return value ? JSON.parse(value) : initialValue;
      } catch (e) {
        // if error, return initial value
        return initialValue;
      }
    }
      window.localStorage.setItem(key, JSON.stringify(value));
      } catch (e) {
        // catch possible errors:
        // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
      }
    }
    
  2. Initialize your state by reading from LocalStorage. E.g.
    const [userId, setUserId] = useState(() => getLocalStorage("userId", ""));
    
  3. Update LocalStorage when state changes. E.g.
    useEffect(() => {
      setLocalStorage("userId", userId);
    }, [userId]);
    

Source