Rendering on Client Only in NextJS


Here is a way to render a React component in the browser only when using NextJS.

To render on the client only, wrap your component in a dynamic import.

With this component in my-component.ts:

'use client'

import React from 'react'
export interface MyComponentProps {}
export function MyComponent(props: MyComponentProps) {
  return <div>client only, baby!</div>
}

I wrap like this in my-component-client.ts:

import dynamic, { DynamicOptions } from 'next/dynamic'
import { MyComponentProps } from './my-component'

export const MyComponent = dynamic(
  import('./my-component')
    .then((mod) => mod.MyComponent)
    .catch((err) =>
      console.error(`Failed to load MyComponent!`, err),
    ) as DynamicOptions<MyComponentProps>,
  {
    ssr: false,
  },
)

And I import from the wrapper:

import { MyComponent } from './my-component-client'

export default function HomePage() {
  return (
    <MyComponent />
  )
}

It will not render on the build server or the app server. It'll only render on the client.

Without the wrapper, and even with the 'use client', the client component will pre-render on the server.