Sidebar state with SSR
Unanswered
Bakharwal dog posted this in #help-forum
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
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
Bakharwal dogOP
so youre saying
useState
will not reset its state when navigating?how?
Bakharwal dogOP
what about when the user full page reloads the page?
then the state resets
Bakharwal dogOP
can you share the link to the screenshot? thanks! @B33fb0n3
Bakharwal dogOP
@B33fb0n3 the docs are misleading,
this issue explains https://github.com/vercel/next.js/issues/58699
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
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
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
@Bakharwal dog solved?
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 🤣
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
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?
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
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.