Next.js Discord

Discord Forum

How to render content from the `window` object on the first paint

Answered
Polar bear posted this in #help-forum
Open in Discord
Avatar
Polar bearOP
Let's say if you want window.localStorage.length to be rendered, you would do something like this:
"use client"
export const Component = () => (
  <div>
    {typeof window !== "undefined" && localStorage.length}
  </div>
);

But the component would initially render as an empty div then change to the actual content (with a hydration mismatch warning).

Is there a way I can render this component as if it is server side rendered? I don't want the content to re-render on the client.

17 Replies

Avatar
import this component with next/dynamic with ssr:false
Avatar
yes, like this
Avatar
Polar bearOP
It's the same for me
the number doesn't show up on the first render
could you try it? let me know if it does
Avatar
that's cause nextjs pre-renders on server and ssr:false tells it to load this component entirely client side
the localStorage.length = is pre rendered on server
whereas the value loads on client
Avatar
Polar bearOP
Yeah. But I also want the value to behave the same
Avatar
that's just not possible because of how nextjs work
Avatar
Polar bearOP
how does nextjs perfectly render a page with dark theme (e.g with next-themes) since the config is kept in localStorage
if that works. I think it should work too in my case
Answer
Avatar
it injects a script in head
you can read this code to do the same
Avatar
Polar bearOP
it works. Thanks a lot manπŸ‘ πŸ‘