Next.js Discord

Discord Forum

How to properly use localStorage browser API in Next 14

Answered
Eurasian Blackbird posted this in #help-forum
Open in Discord
Eurasian BlackbirdOP
Hello and thanks to everyone who will read this and try to help me understand.

My question in title is pretty self explaining but I'd like to explain a bit further.

From what I understand here https://github.com/reactwg/server-components/discussions/4 even if I use "use client" directive at the top of my component, the javascript code will still be executed on the server on first load to create the RSC. And this sounds like a problem when I want to use localStorage, or any webBrowser related API, here is why :
if I have a component defined like this :
'use client';

export default function DisplayLocalStorageOnRootLayout() {
  return <div>{localStorage.getItem('test')}</div>;
}

And that I want to use this component pretty much anywhere (let's say the root layout) :
import DisplayLocalStorageOnRootLayout from '...';

export default function RootLayout({
  children,
}: Readonly<{
  children: ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
        <DisplayLocalStorageOnRootLayout />
        <div>Global Layout</div>
        {children}
      </body>
    </html>
  );
}

This root layout code (including) my component will then be run on the server where localStorage is not defined, therefore, I have this message in my console :
 ⨯ ReferenceError: localStorage is not defined
    at DisplayLocalStorageOnRootLayout (./src/app/localStorage/client/DisaplyLocalStorageOnRootLayout.tsx:10:19)
  2 |
  3 | export default function DisplayLocalStorageOnRootLayout() {
> 4 |   return <div>{localStorage.getItem('test')}</div>;
    |               ^
  5 | }
  6 |

Which completely make sense. But then how can I use localStorage at all ?
The only workaround I found until now is to use useState hook and useEffect hooks to update the value on first mount. But it's just a workaroud.

Thanks again for anyone that's will try to help me.

2 Replies

Answer
@Clown You can do something like this: https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr
Eurasian BlackbirdOP
Perfect ! Exactly what I was looking for ! Thank you