Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Next.js App Router x @apollo/client

Yoshiki Kurihara
September 06, 2023
400

Next.js App Router x @apollo/client

Yoshiki Kurihara

September 06, 2023
Tweet

Transcript

  1. Self introduction Yoshiki Kurihara (@kuriyosh) Work experience Yuimedi (software engineer)

    AWS (cloud support engineer) Skills TypeScript Node.js AWS
  2. Agenda What is Next.js App Router What is @apollo/client Cache

    optimization in app router Server side Client side
  3. What is Next.js App Router React Server Component call API

    closer to data source reduce JS sent to client Stream SSR get page earlier without waiting entire page etc...
  4. Rendering phase in App Router React Server component Client component

    (server side) Client component (client side)
  5. Challenge optimize cache Server side want to share a cache

    with multiple server components one apollo client cannot be used globally Client side needs to share cache in two runtimes (server/client)
  6. @apollo/experimental-nextjs-app-support For server components Create a client instance between server

    components For client components Hydrate query result executed in server side to browser cache
  7. const { getClient } = registerApolloClient(() => { return new

    NextSSRApolloClient({ cache: new NextSSRInMemoryCache(), link: new HttpLink({ uri: ENDPOINT, }), }); }); const QueryFromServer = async ({ index }) => { const { data } = await getClient().query({ query: userQuery }); ... }; const Page = () => { return (
  8. How to provide RSC cache sharing Use React.cache for providing

    client (registerApolloClient) React.cache enables caching callback function for each request Ref: https://zenn.dev/cybozu_frontend/articles/react- cache-and-nextjs
  9. "use client"; const SuspenseQueryUser = ({ children }) => {

    const result = useSuspenseQuery(userQuery); ... }; const QueryUser = ({ children }) => { const result = useQuery(userQuery); ... }; const Page = () => { // call query user only once return ( <Suspense> <SuspenseQueryUser> <QueryUser /> </SuspenseQueryUser> <QueryUser /> </Suspense> ); };
  10. Recap @apollo/experimental-nextjs-app-support provide optimized cache in app router Create a

    client instance between server components → Use React.cache Hydrate query result executed in server side to browser cache → Use ServerInsertedHTMLContext (useServerInsertedHTML )