#Prevent Sidebar Jump on Page Load with localStorage in Next.js

1 messages · Page 1 of 1 (latest)

eager talon
#

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?

midnight fableBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

last eagle
#

store sidebar state in cookies instead

eager talon
last eagle
#
  1. server-side read sidebar state from cookie
  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
eager talon
#

Thanks, but how will writing to the cookie be like, would it be from the server?

last eagle
#

if you want to update sidebar state in server, use server actions with cookies api. otherwise window.document.cookie