Zustand state being triggered server side even though I have "use client"?
Hey all! Recently switched over to Zustand, and quite like it, but I have an issue where my stores' create functions are being called on the server side for some reason?
Take this AudioContext store for example, I had to add the typeof checks because otherwise I would get localStorage doesn't exist. My current theory is that it's being run on the server side, but maybe it's just running before localStorage is mounted (if that's a thing?)
I trigger the stores from a component
that sits in my layout
12 Replies
Use client is very misleading. There are 3 different ways react is loaded/run in next. The first is server components (no state, effects, etc). The second is use client which is wildly misunderstood to run only on the client. Use client files are still fully server side rendered, so during the SSR period that code is still technically running on your server for the initial render
The third type is client only, which you can do via dynamically importing a module and telling next to turn off SSR for that component
i see, what would be the best approach in regards to wanting zustand to only want client side?
And during this SSR period, local storage, window, document, etc are all underground
Well that's the thing, you still want to make everything be server friendly as much as possible cause it helps your initial page loads
that's true, but in this case I'm trying to handle a websocket & audiocontext which only really works client side I think? I don't think those can communicate nicely between boundary layers
same with localstorage
oh! wait
i guess I move my localStorage code out of zustand
and into the store initalizer component that has my useEffect
Correct, so to solve this, simply move your initial volume into a effect and make it a state variable and have it run on load. Anything inside a useEffect will not run during ssr
beautiful, will try that out right now, ty
Correct as in websockets are client side and such
need to really deep dive the use client stuff more for a better understanding
It's very messy
But once you really have the mental model down its very nice in terms of how much is done under the hood for you in terms of perf and such
Also In this case it might make sense for you to just try and import that entire effect dynamically and turn off SSR since it really does directly depend on the client
I ended up moving it into my setupAudio function which only runs client side based on the store init effect
and then just set the zustand store volume based on what the client returns
and it works great! no error 🙂
ty for the pointers
Woo! Great stuff!
Glad I could help
If that's everything feel free to mark the question as solved
already did! 😄