diff --git a/public/images/docs/diagrams/use_client_module_dependency.dark.png b/public/images/docs/diagrams/use_client_module_dependency.dark.png new file mode 100644 index 000000000..c50e7308b Binary files /dev/null and b/public/images/docs/diagrams/use_client_module_dependency.dark.png differ diff --git a/public/images/docs/diagrams/use_client_module_dependency.png b/public/images/docs/diagrams/use_client_module_dependency.png new file mode 100644 index 000000000..d535246f7 Binary files /dev/null and b/public/images/docs/diagrams/use_client_module_dependency.png differ diff --git a/public/images/docs/diagrams/use_client_render_tree.dark.png b/public/images/docs/diagrams/use_client_render_tree.dark.png new file mode 100644 index 000000000..8d3e6a484 Binary files /dev/null and b/public/images/docs/diagrams/use_client_render_tree.dark.png differ diff --git a/public/images/docs/diagrams/use_client_render_tree.png b/public/images/docs/diagrams/use_client_render_tree.png new file mode 100644 index 000000000..ad3840681 Binary files /dev/null and b/public/images/docs/diagrams/use_client_render_tree.png differ diff --git a/src/content/reference/react/directives.md b/src/content/reference/react/directives.md index b323dab1d..4854310b3 100644 --- a/src/content/reference/react/directives.md +++ b/src/content/reference/react/directives.md @@ -19,5 +19,5 @@ Directives provide instructions to [bundlers compatible with React Server Compon ## Source code directives {/*source-code-directives*/} -* [`'use client'`](/reference/react/use-client) marks source files whose components execute on the client. +* [`'use client'`](/reference/react/use-client) lets you mark what code runs on the client. * [`'use server'`](/reference/react/use-server) marks server-side functions that can be called from client-side code. \ No newline at end of file diff --git a/src/content/reference/react/use-client.md b/src/content/reference/react/use-client.md index b1ba1d7ae..e0190d3fe 100644 --- a/src/content/reference/react/use-client.md +++ b/src/content/reference/react/use-client.md @@ -12,7 +12,7 @@ canary: true -`'use client'` marks source files whose components execute on the client. +`'use client'` lets you mark what code runs on the client. @@ -24,37 +24,352 @@ canary: true ### `'use client'` {/*use-client*/} -Add `'use client';` at the very top of a file to mark that the file (including any child components it uses) executes on the client, regardless of where it's imported. +Add `'use client'` at the top of a file to mark the module and its transitive dependencies as client code. -```js +```js {1} 'use client'; import { useState } from 'react'; +import { formatDate } from './formatters'; +import Link from './link'; export default function RichTextEditor(props) { + formatDate(); // ... + return + + // ... +} ``` -When a file marked `'use client'` is imported from a server component, [compatible bundlers](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) will treat the import as the "cut-off point" between server-only code and client code. Components at or below this point in the module graph can use client-only React features like [`useState`](/reference/react/useState). +When a file marked with `'use client'` is imported from a Server Component, [compatible bundlers](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) will treat the module import as a boundary between server-run and client-run code. + +As a dependency of `RichTextEditor`, `formatDate` and `Link` will also be evaluated on the client regardless of whether their modules contain a `'use client'` directive. Note that the same module may be evaluated on the server when imported from server code and on the client when imported from client code. #### Caveats {/*caveats*/} -* It's not necessary to add `'use client'` to every file that uses client-only React features, only the files that are imported from server component files. `'use client'` denotes the _boundary_ between server-only and client code; any components further down the tree will automatically be executed on the client. In order to be rendered from server components, components exported from `'use client'` files must have serializable props. -* When a `'use client'` file is imported from a server file, the imported values can be rendered as a React component or passed via props to a client component. Any other use will throw an exception. -* When a `'use client'` file is imported from another client file, the directive has no effect. This allows you to write client-only components that are simultaneously usable from server and client components. -* All the code in `'use client'` file as well as any modules it imports (directly or indirectly) will become a part of the client module graph and must be sent to and executed by the client in order to be rendered by the browser. To reduce client bundle size and take full advantage of the server, move state (and the `'use client'` directives) lower in the tree when possible, and pass rendered server components [as children](/learn/passing-props-to-a-component#passing-jsx-as-children) to client components. -* Because props are serialized across the server–client boundary, note that the placement of these directives can affect the amount of data sent to the client; avoid data structures that are larger than necessary. -* Components like a `` that use neither server-only nor client-only features should generally not be marked with `'use client'`. That way, they can render exclusively on the server when used from a server component, but they'll be added to the client bundle when used from a client component. -* Libraries published to npm should include `'use client'` on exported React components that can be rendered with serializable props that use client-only React features, to allow those components to be imported and rendered by server components. Otherwise, users will need to wrap library components in their own `'use client'` files which can be cumbersome and prevents the library from moving logic to the server later. When publishing prebundled files to npm, ensure that `'use client'` source files end up in a bundle marked with `'use client'`, separate from any bundle containing exports that can be used directly on the server. -* Client components will still run as part of server-side rendering (SSR) or build-time static site generation (SSG), which act as clients to transform React components' initial render output to HTML that can be rendered before JavaScript bundles are downloaded. But they can't use server-only features like reading directly from a database. -* Directives like `'use client'` must be at the very beginning of a file, above any imports or other code (comments above directives are OK). They must be written with single or double quotes, not backticks. (The `'use xyz'` directive format somewhat resembles the `useXyz()` Hook naming convention, but the similarity is coincidental.) +* `'use client'` must be at the very beginning of a file, above any imports or other code (comments are OK). They must be written with single or double quotes, but not backticks. +* When a `'use client'` module is imported from another client-rendered module, the directive has no effect. +* When a component module contains a `'use client'` directive, any usage of that component is guaranteed to be a Client Component. However, a component can still be evaluated on the client even if it does not have a `'use client'` directive. + * A component usage is considered a Client Component if it is defined in module with `'use client'` directive or when it is a transitive dependency of a module that contains a `'use client'` directive. Otherwise, it is a Server Component. +* Code that is marked for client evaluation is not limited to components. All code that is a part of the client module sub-tree is sent to and run by the client. +* When a server evaluated module imports values from a `'use client'` module, the values must either be a React component or [supported serializable prop values](#passing-props-from-server-to-client-components) to be passed to a Client Component. Any other use case will throw an exception. + +### How `'use client'` marks client code {/*how-use-client-marks-client-code*/} + +In a React app, components are often split into separate files, or [modules](/learn/importing-and-exporting-components#exporting-and-importing-a-component). + +For apps that use React Server Components, the app is server-rendered by default. `'use client'` introduces a server-client boundary in the [module dependency tree](/learn/understanding-your-ui-as-a-tree#the-module-dependency-tree), effectively creating a client-module subtree. + +To better illustrate this, consider the following React Server Component app and its module dependency and render tree. + + + +```js App.js +import FancyText from './FancyText'; +import InspirationGenerator from './InspirationGenerator'; +import Copyright from './Copyright'; + +export default function App() { + return ( + <> + + + + + + ); +} + +``` + +```js FancyText.js +export default function FancyText({title, text}) { + return title + ?

{text}

+ :

{text}

+} +``` + +```js InspirationGenerator.js +'use client'; + +import { useState } from 'react'; +import inspirations from './inspirations'; +import FancyText from './FancyText'; + +export default function InspirationGenerator({children}) { + const [index, setIndex] = useState(0); + const quote = inspirations[index]; + const next = () => setIndex((index + 1) % inspirations.length); + + return ( + <> +

Your inspirational quote is:

+ + + {children} + + ); +} +``` + +```js Copyright.js +export default function Copyright({year}) { + return

©️ {year}

; +} +``` + +```js inspirations.js +export default [ + "Don’t let yesterday take up too much of today.” — Will Rogers", + "Ambition is putting a ladder against the sky.", + "A joy that's shared is a joy made double.", +]; +``` + +```css +.fancy { + font-family: 'Georgia'; +} +.title { + color: #007AA3; + text-decoration: underline; +} +.cursive { + font-style: italic; +} +.small { + font-size: 10px; +} +``` + +
+ + +`'use client'` segments the module dependency tree of the React Server Components app to mark `InspirationGenerator.js` and any of its dependencies as client-rendered. + + +In the module dependency tree of the example app, the `'use client'` directive in `InspirationGenerator.js` marks that module and all of its transitive dependencies as client modules. It creates a subtree of client modules with `InspirationGenerator.js` as the root. + +During render, the framework will server-render the root component and continue through the [render tree](/learn/understanding-your-ui-as-a-tree#the-render-tree), opting-out of evaluating any code imported from client-marked code. + +The server-rendered portion of the render tree is then sent to the client. The client, with its client code downloaded, then completes rendering the rest of the tree. + + +The render tree for the React Server Components app. `InspirationGenerator` and its child component `FancyText` are components exported from client-marked code and considered Client Components. + + +We introduce the following definitions: + +* **Client Components** are components in a render tree that are rendered on the client. +* **Server Components** are components in a render tree that are rendered on the server. + +Working through the example app, `App`, `FancyText` and `Copyright` are all server-rendered and considered Server Components. As `InspirationGenerator.js` and its transitive dependencies are marked as client code, the component `InspirationGenerator` and its child component `FancyText` are Client Components. + + +#### How is `FancyText` both a Server and a Client Component? {/*how-is-fancytext-both-a-server-and-a-client-component*/} + +By the above definitions, the component `FancyText` is both a Server and Client Component, how can that be? + +First, let's clarify that the term "component" is not very precise. Here are just two ways "component" can be understood: + +1. A "component" can refer to a **component definition**. In most cases this will be a function. + +```js +// This is a definition of a component +function MyComponent() { + return

My Component

+} +``` + +2. A "component" can also refer to a **component usage** of its definition. +```js +import MyComponent from './MyComponent'; + +function App() { + // This is a usage of a component + return ; +} +``` + +Often, the imprecision is not important when explaining concepts, but in this case it is. + +When we talk about Server or Client Components, we are referring to component usages. + +* If the component is defined in a module with a `'use client'` directive, or the component is imported and called in a Client Component, then the component usage is a Client Component. +* Otherwise, the component usage is a Server Component. + + +A render tree illustrates component usages. + +Back to the question of `FancyText`, we see that the component definition does _not_ have a `'use client'` directive and it has two usages. + +The usage of `FancyText` as a child of `App`, marks that usage as a Server Component. When `FancyText` is imported and called under `InspirationGenerator`, that usage of `FancyText` is a Client Component as `InspirationGenerator` contains a `'use client'` directive. + +This means that the component definition for `FancyText` will both be evaluated on the server and also downloaded by the client to render its Client Component usage. + +
+ + + +#### Why is `Copyright` a Server Component? {/*why-is-copyright-a-server-component*/} + +As a child of `InspirationGenerator`, a Client Component, why is `Copyright` a Server Component? + +To clarify, `'use client'` defines the boundary between server and client code on the _module dependency tree_, not the render tree. + + +`'use client'` defines the boundary between server and client code on the module dependency tree. + + +In the module dependency tree, we see that `App.js` imports and calls `Copyright` from the `Copyright.js` module. As `Copyright.js` does not contain a `'use client'` directive, the component usage is rendered on the server. `App` is rendered on the server as it is the root component. + +Client Components can render Server Components because you can pass JSX as props. In this case, `InspirationGenerator` receives `Copyright` as [children](/learn/passing-props-to-a-component#passing-jsx-as-children). However, the `InspirationGenerator` module never directly imports the `Copyright` module nor calls the component, all of that is done by `App`. + +The takeaway is that a parent-child render relationship between components does not guarantee the same render environment. + + + +### When to use `'use client'` {/*when-to-use-use-client*/} + +With `'use client'`, you can determine what component usages will be 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 {/*advantages*/} +* 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 {/*limitations*/} +* Server Components cannot support interaction as event handlers must be registered and triggered by a client. + * The browser, as an example client, is responsible for delegating UI clicks to the appropriate `onClick` handler. +* Server Components cannot use most Hooks. + * When Server Components are rendered, they are conceptually resolved into instructions for the client to interpret and turn into UI primitives. This means that Server Components do not persist in memory after render and do not support re-rendering or state. + +### Passing props from Server to Client Components {/*passing-props-from-server-to-client-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](https://developer.mozilla.org/en-US/docs/Glossary/String) + * [number](https://developer.mozilla.org/en-US/docs/Glossary/Number) + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) + * [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean) + * [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined) + * [null](https://developer.mozilla.org/en-US/docs/Glossary/Null) + * [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) +* Iterables containing serializable values + * [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) + * [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) + * [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) + * [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) + * [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) +* [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) +* [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) +* Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties +* Client or Server Components +* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) + +Notably, these are not supported: +* [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that are not exported from client-marked modules or marked with [`'use server'`](/reference/react/use-server) +* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) +* Objects that are instances of any class (other than built-ins mentioned) or objects with [null-prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) +* Symbols not registered globally, ex. `Symbol('my new symbol')` + ## Usage {/*usage*/} - -This section is a work in progress. +### Building with interactivity and state {/*building-with-interactivity-and-state*/} + + + +```js 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 {getCounterValueFromFile} from 'fs-utils'; +import Counter from './Counter'; + +export default async function CounterContainer() { + const initialValue = await getCounterValueFromFile(); + return +} +``` + +For example, the parent component of the Client 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. This is possible because Server Components, unlike Client Components, can be async functions. + +There are also components that don't use any server or client-only features and can be agnostic to where they render. `FancyText` is an example of such a component. + +```js +export default function FancyText({title, text}) { + return title + ?

{text}

+ :

{text}

+} +``` + +In this case, it is discouraged to use the `'use client'` directive as it prematurely forces all component usages of `FancyText` to be rendered on the client, which comes at a performance cost. 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. + +### Using client APIs {/*using-client-apis*/} + +Your React app may use client-specific APIs which are dependent on your targeted client. For the browser, some example client APIs include web storage, audio and video manipulation, and device hardware, among [others](https://developer.mozilla.org/en-US/docs/Web/API). + +In this example, the component uses [DOM APIs](https://developer.mozilla.org/en-US/docs/Glossary/DOM) to manipulate a [`canvas`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. Since those APIs are only available in the browser, it must be marked as a Client Component. + +```js +'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.beginPath(); + context.arc(100, 75, 50, 0, 2 * Math.PI); + context.stroke(); + }); + return +} +``` + +### Using React libraries {/*using-react-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. In these cases, you'll need to ensure you're using these libraries in Client Components. Depending on the nature of these libraries, this may mean adding a `'use client'` near the top of your module dependency tree – marking the majority of your React app as client-rendered. + +Libraries that use any of the following React APIs must be marked as client-run: +* [createContext](/reference/react/createContext) +* [`react`](/reference/react/hooks) and [`react-dom`](/reference/react-dom/hooks) Hooks, excluding [`use`](/reference/react/use) and [`useId`](/reference/react/useId) +* [forwardRef](/reference/react/forwardRef) +* [memo](/reference/react/memo) +* [startTransition](/reference/react/startTransition) +* If they use client APIs, ex. DOM insertion or native platform views -This API can be used in any framework that supports React Server Components. You may find additional documentation from them. -* [Next.js documentation](https://nextjs.org/docs/getting-started/react-essentials) -* More coming soon -
\ No newline at end of file +[TODO]: <> (Troubleshooting - need use-cases) \ No newline at end of file