Search code examples
reactjsnext.jsprop-drilling

How to prevent prop drilling with SSR in Next


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.


Solution

  • 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