Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hydration Error in updating isExpanded state from LocalStorage #2

Open
HarshArora-1205 opened this issue Jul 26, 2024 · 3 comments
Open

Comments

@HarshArora-1205
Copy link

const [isSidebarExpanded, setIsSidebarExpanded] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = window.localStorage.getItem('sidebarExpanded');
      if (saved === null) {
        return true;
      }
      return JSON.parse(saved);
    }
    return true; // default state if window is not defined
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(
        'sidebarExpanded',
        JSON.stringify(isSidebarExpanded),
      );
    }
  }, [isSidebarExpanded]);

  const toggleSidebar = () => {
    setIsSidebarExpanded(!isSidebarExpanded);
  };

Error: Hydration failed because the initial UI does not match what was rendered on the server.

This particular part brings Hydration Error. So for that I used 2 useEffects instead of directly initializing via function and created a mounted state to check if component is mounted or not. Then track the state changes.

Want to know if there is something else that can be done and is efficient.

my updates:

const [isCollapsed, setIsCollapsed] = useState<boolean>(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const saved = window.localStorage.getItem("sidebarCollapsed");
      if (saved !== null) {
        setIsCollapsed(JSON.parse(saved));
      }
      setMounted(true);
    }
  }, []);

  useEffect(() => {
    if (mounted && typeof window !== "undefined") {
      window.localStorage.setItem("sidebarCollapsed", JSON.stringify(isCollapsed));
    }
  }, [isCollapsed, mounted]);

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };

Here I am using isCollapsed instead of isExpanded.

@cozarkd
Copy link

cozarkd commented Aug 23, 2024

Same problem here. Are you happy with this solution?

@HarshArora-1205
Copy link
Author

Hi.

Worked fine for me. If you find any better workaround , do let me know.

@HarshArora-1205
Copy link
Author

@hqasmei Can you check this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants