'use client'·续

When to use 'use client'

With 'use client', you can determine when components are Client Components. As Server Components are default, here is a brief overview of the advantages and limitations to Server Components to determine when you need to mark something as client rendered.

For simplicity, we talk about Server Components, but the same principles apply to all code in your app that is server run.

Advantages of Server Components

  • Server Components can reduce the amount of code sent and run by the client. Only Client modules are bundled and evaluated by the client.
  • Server Components benefit from running on the server. They can access the local filesystem and may experience low latency for data fetches and network requests.

Limitations of Server Components

  • Server Components cannot support interaction as event handlers must be registered and triggered by a client.
    • For example, event handlers like onClick can only be defined in Client Components.
  • Server Components cannot use most Hooks.
    • When Server Components are rendered, their output is essentially a list of components for the client to render. Server Components do not persist in memory after render and cannot have their own state.

Serializable types returned by Server Components

As in any React app, parent components pass data to child components. As they are rendered in different environments, passing data from a Server Component to a Client Component requires extra consideration.

Prop values passed from a Server Component to Client Component must be serializable.

Serializable props include: * Primitives * string * number * bigint * boolean * undefined * null * symbol, only symbols registered in the global Symbol registry via Symbol.for * Iterables containing serializable values * String * Array * Map * Set * TypedArray and ArrayBuffer * Date * Plain objects: those created with object initializers, with serializable properties * Functions that are Server Functions * Client or Server Component elements (JSX) * Promises

Notably, these are not supported: * Functions that are not exported from client-marked modules or marked with 'use server' * Classes * Objects that are instances of any class (other than the built-ins mentioned) or objects with a null prototype * Symbols not registered globally, ex. Symbol('my new symbol')

Usage

Building with interactivity and state

```js src/App.js 'use client';

import { useState } from 'react';

export default function Counter({initialValue = 0}) { const [countValue, setCountValue] = useState(initialValue); const increment = () => setCountValue(countValue + 1); const decrement = () => setCountValue(countValue - 1); return ( <>

Count Value: {countValue}

</> ); }


As `Counter` requires both the `useState` Hook and event handlers to increment or decrement the value, this component must be a Client Component and will require a `'use client'` directive at the top.

In contrast, a component that renders UI without interaction will not need to be a Client Component.

```js
import { readFile } from 'node:fs/promises';
import Counter from './Counter';

export default async function CounterContainer() {
  const initialValue = await readFile('/path/to/counter_value');
  return <Counter initialValue={initialValue} />
}

For example, Counter's parent component, CounterContainer, does not require 'use client' as it is not interactive and does not use state. In addition, CounterContainer must be a Server Component as it reads from the local file system on the server, which is possible only in a Server Component.

There are also components that don't use any server or client-only features and can be agnostic to where they render. In our earlier example, FancyText is one such component.

export default function FancyText({title, text}) {
  return title
    ? <h1 className='fancy title'>{text}</h1>
    : <h3 className='fancy cursive'>{text}</h3>
}

In this case, we don't add the 'use client' directive, resulting in FancyText's output (rather than its source code) to be sent to the browser when referenced from a Server Component. As demonstrated in the earlier Inspirations app example, FancyText is used as both a Server or Client Component, depending on where it is imported and used.

But if FancyText's HTML output was large relative to its source code (including dependencies), it might be more efficient to force it to always be a Client Component. Components that return a long SVG path string are one case where it may be more efficient to force a component to be a Client Component.

Using client APIs

Your React app may use client-specific APIs, such as the browser's APIs for web storage, audio and video manipulation, and device hardware, among others.

In this example, the component uses DOM APIs to manipulate a canvas element. Since those APIs are only available in the browser, it must be marked as a Client Component.

'use client';

import {useRef, useEffect} from 'react';

export default function Circle() {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const canvas = ref.current;
    const context = canvas.getContext('2d');
    context.reset();
    context.beginPath();
    context.arc(100, 75, 50, 0, 2 * Math.PI);
    context.stroke();
  });
  return <canvas ref={ref} />;
}

Using third-party libraries

Often in a React app, you'll leverage third-party libraries to handle common UI patterns or logic.

These libraries may rely on component Hooks or client APIs. Third-party components that use any of the following React APIs must run on the client: * createContext * react and react-dom Hooks, excluding use and useId * forwardRef * memo * startTransition * If they use client APIs, ex. DOM insertion or native platform views

If these libraries have been updated to be compatible with React Server Components, then they will already include 'use client' markers of their own, allowing you to use them directly from your Server Components. If a library hasn't been updated, or if a component needs props like event handlers that can only be specified on the client, you may need to add your own Client Component file in between the third-party Client Component and your Server Component where you'd like to use it.


Sitemap

Overview of all docs pages