Prevent content flicker on the initial render
Unanswered
Giant panda posted this in #help-forum
Giant pandaOP
I have this Layout file which contains a sidebar and the state whether it is opened or not I store in local storage.
The problem is when on the server the local storage is not available, the layout renders as if the sidebar was closed - but when during rendering it reads the local storage and it says sidebar should be open, it causes a flicker.
Here is the code, see the margin (
The problem is when on the server the local storage is not available, the layout renders as if the sidebar was closed - but when during rendering it reads the local storage and it says sidebar should be open, it causes a flicker.
Here is the code, see the margin (
"sm:ml-64": showSidebar
) I am using when showSidebar
is true. That causes problem. What are some ways to overcome such problems?"use client";
import Sidebar from "@/components/client/sidebar";
import React from "react";
import clsx from "clsx";
import Header from "@/components/client/header";
import useLocalStorage from "@/hooks/useLocalStorage";
import { useIsClient } from "@uidotdev/usehooks";
export default function Layout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [showSidebar, setShowSideBar] = useLocalStorage("movie-app", false);
return (
<div lang="en" className="h-full flex">
<Sidebar
isOpen={showSidebar}
close={() => {
setShowSideBar(false);
}}
/>
<div
className={clsx("flex-1 flex flex-col h-full", {
"sm:ml-64": showSidebar,
"transition-[margin-left] duration-300 ease-in-out": shouldAnimate,
})}
>
<Header
toggleSideBar={() => {
setShowSideBar(!showSidebar);
}}
/>
<div className="flex-1 min-h-0">{children}</div>
</div>
</div>
);
}