Prevent Sidebar Jump on Page Load with localStorage in Next.js
Unanswered
Atlantic herring posted this in #help-forum
Atlantic herringOP
Hi everyone, I’m running into an issue with a sidebar in my Next.js app. When a user toggles the sidebar, I save the state to localStorage. The problem is that when the page loads, the sidebar “jumps” — it initially renders with the default style and then quickly switches to the style based on the saved localStorage value.
I’d like to apply the last saved state before the page renders to avoid this jump. Does anyone have advice on the best approach to handle this in Next.js?
I’d like to apply the last saved state before the page renders to avoid this jump. Does anyone have advice on the best approach to handle this in Next.js?
6 Replies
Pacific sand lance
store sidebar state in cookies instead
@Pacific sand lance store sidebar state in cookies instead
Atlantic herringOP
But the sidebar uses an onClick function and useState, how do I handle the issue?
Pacific sand lance
1. server-side read sidebar state from cookie
2. pass sidebar state to sidebar (i.e.
3. client-side use
2. pass sidebar state to sidebar (i.e.
defaultOpen={sidebarCookie?sidebarCookie.value==="open":true}
)3. client-side use
window.document.cookie
instead of window.localStorage
Atlantic herringOP
Thanks, but how will writing to the cookie be like, would it be from the server?
Pacific sand lance
if you want to update sidebar state in server, use server actions with cookies api. otherwise window.document.cookie
Atlantic herringOP
Okay, thanks