#Local Storage and Custom Hook

2 messages · Page 1 of 1 (latest)

fallen compass
#

Hi Guys
I have this custom hook:

import { useRecoilState } from "recoil";
import { sidebarSizeState } from "../atoms/sidebarSize.atom";
import { useEffect } from "react";

const useSidebarSize = () => {
  const [sidebarSize, setSidebarSize] = useRecoilState(sidebarSizeState);

  useEffect(() => {
    if (localStorage && localStorage.getItem("sidebarSize")) {
      setSidebarSize(localStorage.getItem("sidebarSize") as "full" | "compact");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (localStorage) {
      localStorage.setItem("sidebarSize", sidebarSize);
    }
  }, [sidebarSize]);

  const changeSidebarSize = () => {
    setSidebarSize((prevState) => (prevState === "full" ? "compact" : "full"));
  };

  return {
    isCompactSize: sidebarSize === "compact",
    sidebarSize,
    changeSidebarSize,
  };
};

export { useSidebarSize };

But when I refresh the page, the local storage value is overrided by default value and I can't store that value and reuse it.
Any solution?

karmic condor
#

Drop the 2nd useEffect and try this:

const changeSidebarSize = () => {
  setSidebarSize(prevState => {
    const newState = prevState === "full" ? "compact" : "full";
    if (localStorage) {
      localStorage.setItem("sidebarSize", newState);
    }
    return newState;
  });
};