Menu

One Line in My Root Layout Turned 158 Static Pages Into 0
πŸ“°

One Line in My Root Layout Turned 158 Static Pages Into 0

DEV Community: nextjsΒ·Mohsen FallahnejadΒ·7 days ago
#WKkRdQe6
#devtonextjs#devto#dev#dynamic#build
Reading 0:00
15s threshold

Dark mode on this blog has always had a tiny cheat in it. Before React loads, a little inline script reads your saved theme from localStorage and paints the page dark. It works, but it always felt like a hack. The server renders the page without knowing your theme, and a script patches it up in the browser.

The "proper" fix seemed obvious. Store the theme in a cookie, read it on the server, render the right class from the start. One line in the root layout:

// app/layout.tsx import { cookies } from " next/headers " ;

export default async function RootLayout ({ children }) { const theme = ( await cookies ()). get ( " theme " )?. value ;

return ( < html lang = "en" className = { theme === " dark " ? " dark " : undefined } > { /* ... */ } </ html > ); }

Enter fullscreen mode

Exit fullscreen mode

I tried it on a copy of this blog. Dark mode worked on the very first byte. No script, no patching.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.