0

I'm wondering how I can prevent prop drilling with SSR in the following situation:

Layout.tsx:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await getUser(cookies().get("accessToken")?.value);

  return (
    <html lang="en">
      <body>
        <Navigation user={user}
        {children}
      </body>
    </html>
  );
}

Now imagine in Navigation there are multiple nested components that require the user. Normally I'd use the store to pass down data like this but now I'm a bit clueless.

Gugu72
  • 2,052
  • 13
  • 35
Alexander
  • 396
  • 1
  • 9
  • 19

1 Answers1

1

Call getUser(cookies().get("accessToken")?.value) in the child components. This works because requests with the same path and input are automatically deduped by Next's polyfill of fetch.

From docs:

If you need to fetch the same data (e.g. current user) in multiple components in a tree, Next.js will automatically cache fetch requests (GET) that have the same input in a temporary cache. This optimization prevents the same data from being fetched more than once during a rendering pass.

Note: if you are not using fetch then use Next's cache feature

Asplund
  • 2,254
  • 1
  • 8
  • 19