Next.js Discord

Discord Forum

Sidebar state with SSR

Unanswered
Bakharwal dog posted this in #help-forum
Open in Discord
Avatar
Bakharwal dogOP
I'm using a cookie to store the state of my sidebar which includes which sections are expanded and the scrolling position. is this the best practice? is there another way to do it? because without it the state resets in navigation

29 Replies

Avatar
using cookies for that is not a good pratice. This should be handled by the client. So handle the state on the client. For example using a useState. This state will also persists when the browser cache is enabled
Avatar
Bakharwal dogOP
so youre saying useState will not reset its state when navigating?
how?
Avatar
yes, it saved inside the browser cache and is preserved
Image
Avatar
Bakharwal dogOP
what about when the user full page reloads the page?
Avatar
then the state resets
Avatar
Bakharwal dogOP
can you share the link to the screenshot? thanks! @B33fb0n3
Avatar
Bakharwal dogOP
@B33fb0n3 the docs are misleading,
Avatar
Blanc de Hotot
use a query param
easy life, built in state controller by the browser
depending on the use case it's useful if you need to copy the link to someone when ther is an issue
Avatar
it works clearly fine as you can see here: https://codesandbox.io/p/devbox/xn54j6

This is a reproduction of the solution perfectly matching to your use case.

How to test?
1. Scroll down the sidebar on the left
2. Click the red Link or the sections
3. See Results -> Even if you switch the route, the scrolling position and the expanded sections (the Colors above the red link) persists
Avatar
@Bakharwal dog solved?
Avatar
Blanc de Hotot
You ssr a sidebar?
Oh shit, not a slide out sidebar that's has like form stuff on it
A literal sidebar nav 🤣
Avatar
Bakharwal dogOP
@B33fb0n3 it was solved by not having 2 layout.tsx
not sure why, it stopped re-rendering when I put the sidebar in the main layout
so I didn't lose the scroll position on navigation
Avatar
So you now leveraging the browser cache to persists the states and you now using client side states that are handled by the client, right?
Avatar
Bakharwal dogOP
it doesnt even re-render, when i turn on the react dev chrome extension
the scroll bar is not part of the state
the only reason it doesn't reset - means it did not unmount
would you mind taking a look at my new problem? lol
Avatar
Yea, the scroll bar position is only saved inside the browser cache. And due no rerender of the layout all states persists as well
I'll help you with this one, but I don't think I'll be able to help you with future issues. It's a bit too much work to write inside your threads.