antonwilhelm
antonwilhelm

Reputation: 7553

Will the Provider render my whole App client-side?

I am following this PostHog tutorial and it involves wrapping my whole app in the PostHogProvider, which has a use client directive. Will this effectively turn my whole app into a client side app and opt me out of Next.js server components?

// app/providers.js
'use client'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'

export default function PHProvider({ children, bootstrapData }) {
  if (typeof window !== 'undefined') {
    posthog.init("<ph_project_api_key>", {
      api_host: "https://us.i.posthog.com",
      bootstrap: bootstrapData
    })
  }

  return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}

Upvotes: 2

Views: 113

Answers (2)

NickDGreg
NickDGreg

Reputation: 484

It won't. At least with Nextjs App router because it is able to interleave client and server components:

When interleaving Client and Server Components, it may be helpful to visualize your UI as a tree of components. Starting with the root layout, which is a Server Component, you can then render certain subtrees of components on the client by adding the "use client" directive.

Within those client subtrees, you can still nest Server Components or call Server Actions.

From the Posthog docs:

Does wrapping my app in the PostHog provider de-opt it to client-side rendering?

No. Even though the PostHog provider is a client component, since we pass the children prop to it, any component inside the children tree can still be a server component. Next.js creates a boundary between server-run and client-run code.

The use client reference says that it "defines the boundary between server and client code on the module dependency tree, not the render tree." It also says that "During render, the framework will server-render the root component and continue through the render tree, opting-out of evaluating any code imported from client-marked code."

Pages router components are client components by default.

Upvotes: 0

Abolfazl Jamshidi
Abolfazl Jamshidi

Reputation: 73

According to Next.js documents and using the app router, every component which is rendered inside a client component will automatically become a part of the client bundle. You take a look at this point here: https://nextjs.org/docs/app/building-your-application/rendering/client-components#using-client-components-in-nextjs

Upvotes: 0

Related Questions