Browse Source

[Beta] Move Reference before Usage (#5399)

* [Beta] Move Reference before Usage

* above -> below
main
dan 2 years ago
committed by GitHub
parent
commit
147bab9196
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 208
      beta/src/content/apis/react-dom/client/createRoot.md
  2. 198
      beta/src/content/apis/react-dom/client/hydrateRoot.md
  3. 1716
      beta/src/content/apis/react-dom/components/common.md
  4. 162
      beta/src/content/apis/react-dom/components/input.md
  5. 57
      beta/src/content/apis/react-dom/components/option.md
  6. 43
      beta/src/content/apis/react-dom/components/progress.md
  7. 115
      beta/src/content/apis/react-dom/components/select.md
  8. 122
      beta/src/content/apis/react-dom/components/textarea.md
  9. 81
      beta/src/content/apis/react-dom/createPortal.md
  10. 78
      beta/src/content/apis/react-dom/findDOMNode.md
  11. 68
      beta/src/content/apis/react-dom/flushSync.md
  12. 86
      beta/src/content/apis/react-dom/hydrate.md
  13. 102
      beta/src/content/apis/react-dom/render.md
  14. 51
      beta/src/content/apis/react-dom/server/renderToNodeStream.md
  15. 94
      beta/src/content/apis/react-dom/server/renderToPipeableStream.md
  16. 100
      beta/src/content/apis/react-dom/server/renderToReadableStream.md
  17. 55
      beta/src/content/apis/react-dom/server/renderToStaticMarkup.md
  18. 56
      beta/src/content/apis/react-dom/server/renderToStaticNodeStream.md
  19. 57
      beta/src/content/apis/react-dom/server/renderToString.md
  20. 66
      beta/src/content/apis/react-dom/unmountComponentAtNode.md
  21. 330
      beta/src/content/apis/react/Children.md
  22. 2610
      beta/src/content/apis/react/Component.md
  23. 38
      beta/src/content/apis/react/Fragment.md
  24. 85
      beta/src/content/apis/react/Profiler.md
  25. 48
      beta/src/content/apis/react/PureComponent.md
  26. 72
      beta/src/content/apis/react/StrictMode.md
  27. 34
      beta/src/content/apis/react/Suspense.md
  28. 104
      beta/src/content/apis/react/cloneElement.md
  29. 164
      beta/src/content/apis/react/createContext.md
  30. 98
      beta/src/content/apis/react/createElement.md
  31. 80
      beta/src/content/apis/react/createFactory.md
  32. 80
      beta/src/content/apis/react/createRef.md
  33. 114
      beta/src/content/apis/react/forwardRef.md
  34. 70
      beta/src/content/apis/react/isValidElement.md
  35. 64
      beta/src/content/apis/react/lazy.md
  36. 56
      beta/src/content/apis/react/memo.md
  37. 57
      beta/src/content/apis/react/startTransition.md
  38. 78
      beta/src/content/apis/react/useCallback.md
  39. 64
      beta/src/content/apis/react/useContext.md
  40. 57
      beta/src/content/apis/react/useDebugValue.md
  41. 86
      beta/src/content/apis/react/useDeferredValue.md
  42. 108
      beta/src/content/apis/react/useEffect.md
  43. 63
      beta/src/content/apis/react/useId.md
  44. 68
      beta/src/content/apis/react/useImperativeHandle.md
  45. 88
      beta/src/content/apis/react/useInsertionEffect.md
  46. 94
      beta/src/content/apis/react/useLayoutEffect.md
  47. 80
      beta/src/content/apis/react/useMemo.md
  48. 144
      beta/src/content/apis/react/useReducer.md
  49. 76
      beta/src/content/apis/react/useRef.md
  50. 150
      beta/src/content/apis/react/useState.md
  51. 86
      beta/src/content/apis/react/useSyncExternalStore.md
  52. 144
      beta/src/content/apis/react/useTransition.md

208
beta/src/content/apis/react-dom/client/createRoot.md

@ -16,6 +16,110 @@ const root = createRoot(domNode, options?)
---
## Reference {/*reference*/}
### `createRoot(domNode, options?)` {/*createroot*/}
Call `createRoot` to create a React root for displaying content inside a browser DOM element.
```js
const domNode = document.getElementById('root');
const root = createRoot(domNode);
```
React will create a root for the `domNode`, and take over managing the DOM inside it. After you've created a root, you need to call [`root.render`](#root-render) to display a React component inside of it:
```js
root.render(<App />);
```
An app fully built with React will usually only have one `createRoot` call for its root component. A page that uses "sprinkles" of React for parts of the page may have as many separate roots as needed.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will create a root for this DOM element and allow you to call functions on the root, such as `render` to display rendered React content.
* **optional** `options`: An object with options for this React root.
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page.
#### Returns {/*returns*/}
`createRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
#### Caveats {/*caveats*/}
* If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead.
* You'll likely have only one `createRoot` call in your app. If you use a framework, it might do this call for you.
* When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use [`createPortal`](/apis/react-dom/createPortal) instead of `createRoot`.
---
### `root.render(reactNode)` {/*root-render*/}
Call `root.render` to display a piece of [JSX](/learn/writing-markup-with-jsx) ("React node") into the React root's browser DOM node.
```js
root.render(<App />);
```
React will display `<App />` in the `root`, and take over managing the DOM inside it.
[See more examples below.](#usage)
#### Parameters {/*root-render-parameters*/}
* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
`root.render` returns `undefined`.
#### Caveats {/*root-render-caveats*/}
* The first time you call `root.render`, React will clear all the existing HTML content inside the React root before rendering the React component into it.
* If your root's DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead, which attaches the event handlers to the existing HTML.
* If you call `render` on the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same root again is similar to calling the [`set` function](/apis/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.
---
### `root.unmount()` {/*root-unmount*/}
Call `root.unmount` to destroy a rendered tree inside a React root.
```js
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters {/*root-unmount-parameters*/}
`root.unmount` does not accept any parameters.
#### Returns {/*root-unmount-returns*/}
`root.unmount` returns `undefined`.
#### Caveats {/*root-unmount-caveats*/}
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
* Once you call `root.unmount` you cannot call `root.render` again on the same root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. However, you can create a new root for the same DOM node after the previous root for that node has been unmounted.
---
## Usage {/*usage*/}
### Rendering an app fully built with React {/*rendering-an-app-fully-built-with-react*/}
@ -231,110 +335,6 @@ export default function App({counter}) {
It is uncommon to call `render` multiple times. Usually, you'll [update state](/apis/react/useState) inside one of the components instead.
---
## Reference {/*reference*/}
### `createRoot(domNode, options?)` {/*createroot*/}
Call `createRoot` to create a React root for displaying content inside a browser DOM element.
```js
const domNode = document.getElementById('root');
const root = createRoot(domNode);
```
React will create a root for the `domNode`, and take over managing the DOM inside it. After you've created a root, you need to call [`root.render`](#root-render) to display a React component inside of it:
```js
root.render(<App />);
```
An app fully built with React will usually only have one `createRoot` call for its root component. A page that uses "sprinkles" of React for parts of the page may have as many separate roots as needed.
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will create a root for this DOM element and allow you to call functions on the root, such as `render` to display rendered React content.
* **optional** `options`: An object with options for this React root.
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page.
#### Returns {/*returns*/}
`createRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
#### Caveats {/*caveats*/}
* If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead.
* You'll likely have only one `createRoot` call in your app. If you use a framework, it might do this call for you.
* When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use [`createPortal`](/apis/react-dom/createPortal) instead of `createRoot`.
---
### `root.render(reactNode)` {/*root-render*/}
Call `root.render` to display a piece of [JSX](/learn/writing-markup-with-jsx) ("React node") into the React root's browser DOM node.
```js
root.render(<App />);
```
React will display `<App />` in the `root`, and take over managing the DOM inside it.
[See examples above.](#usage)
#### Parameters {/*root-render-parameters*/}
* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
`root.render` returns `undefined`.
#### Caveats {/*root-render-caveats*/}
* The first time you call `root.render`, React will clear all the existing HTML content inside the React root before rendering the React component into it.
* If your root's DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead, which attaches the event handlers to the existing HTML.
* If you call `render` on the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same root again is similar to calling the [`set` function](/apis/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.
---
### `root.unmount()` {/*root-unmount*/}
Call `root.unmount` to destroy a rendered tree inside a React root.
```js
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters {/*root-unmount-parameters*/}
`root.unmount` does not accept any parameters.
#### Returns {/*root-unmount-returns*/}
`root.unmount` returns `undefined`.
#### Caveats {/*root-unmount-caveats*/}
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
* Once you call `root.unmount` you cannot call `root.render` again on the same root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. However, you can create a new root for the same DOM node after the previous root for that node has been unmounted.
---
## Troubleshooting {/*troubleshooting*/}
### I've created a root, but nothing is displayed {/*ive-created-a-root-but-nothing-is-displayed*/}

198
beta/src/content/apis/react-dom/client/hydrateRoot.md

@ -16,6 +16,105 @@ const root = hydrateRoot(domNode, reactNode, options?)
---
## Reference {/*reference*/}
### `hydrateRoot(domNode, options?)` {/*hydrateroot*/}
Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
```js
const domNode = document.getElementById('root');
const root = hydrateRoot(domNode, reactNode);
```
React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream(<App />)`.
* **optional** `options`: An object with options for this React root.
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
* **optional** `nonce`:
#### Returns {/*returns*/}
`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
#### Caveats {/*caveats*/}
* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them.
* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you.
* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/apis/react-dom/client/createRoot) instead.
---
### `root.render(reactNode)` {/*root-render*/}
Call `root.render` to update a React component inside a hydrated React root for a browser DOM element.
```js
root.render(<App />);
```
React will update `<App />` in the hydrated `root`.
[See more examples below.](#usage)
#### Parameters {/*root-render-parameters*/}
* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
`root.render` returns `undefined`.
#### Caveats {/*root-render-caveats*/}
* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering.
---
### `root.unmount()` {/*root-unmount*/}
Call `root.unmount` to destroy a rendered tree inside a React root.
```js
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters {/*root-unmount-parameters*/}
`root.unmount` does not accept any parameters.
#### Returns {/*root-unmount-returns*/}
`render` returns `null`.
#### Caveats {/*root-unmount-caveats*/}
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
* Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error.
---
## Usage {/*usage*/}
### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
@ -270,102 +369,3 @@ export default function App({counter}) {
</Sandpack>
It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/apis/react/useState) inside one of the components instead.
---
## Reference {/*reference*/}
### `hydrateRoot(domNode, options?)` {/*hydrateroot*/}
Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
```js
const domNode = document.getElementById('root');
const root = hydrateRoot(domNode, reactNode);
```
React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component.
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream(<App />)`.
* **optional** `options`: An object with options for this React root.
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
* **optional** `nonce`:
#### Returns {/*returns*/}
`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
#### Caveats {/*caveats*/}
* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them.
* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you.
* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/apis/react-dom/client/createRoot) instead.
---
### `root.render(reactNode)` {/*root-render*/}
Call `root.render` to update a React component inside a hydrated React root for a browser DOM element.
```js
root.render(<App />);
```
React will update `<App />` in the hydrated `root`.
[See examples above.](#usage)
#### Parameters {/*root-render-parameters*/}
* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
`root.render` returns `undefined`.
#### Caveats {/*root-render-caveats*/}
* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering.
---
### `root.unmount()` {/*root-unmount*/}
Call `root.unmount` to destroy a rendered tree inside a React root.
```js
root.unmount();
```
An app fully built with React will usually not have any calls to `root.unmount`.
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions.
Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
#### Parameters {/*root-unmount-parameters*/}
`root.unmount` does not accept any parameters.
#### Returns {/*root-unmount-returns*/}
`render` returns `null`.
#### Caveats {/*root-unmount-caveats*/}
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
* Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error.

1716
beta/src/content/apis/react-dom/components/common.md

File diff suppressed because it is too large

162
beta/src/content/apis/react-dom/components/input.md

@ -16,6 +16,87 @@ The [built-in browser `<input>` component](https://developer.mozilla.org/en-US/d
---
## Reference {/*reference*/}
### `<input>` {/*input*/}
To display an input, render the [built-in browser `<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) component.
```js
<input name="myInput" />
```
[See more examples below.](#usage)
#### Props {/*props*/}
`<input>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make an input controlled](#controlling-an-input-with-a-state-variable) by passing one of these props:
* [`checked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#checked): A boolean. For a checkbox input or a radio button, controls whether it is selected.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#value): A string. For a text input, controls its text. (For a radio button, specifies its form data.)
When you pass either of them, you must also pass an `onChange` handler that updates the passed value.
These `<input>` props are only relevant for uncontrolled inputs:
* [`defaultChecked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#defaultChecked): A boolean. Specifies [the initial value](#providing-an-initial-value-for-an-input) for `type="checkbox"` and `type="radio"` inputs.
* [`defaultValue`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#defaultValue): A string. Specifies [the initial value](#providing-an-initial-value-for-an-input) for a text input.
These `<input>` props are relevant both for uncontrolled and controlled inputs:
* [`accept`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#accept): A string. Specifies which filetypes are accepted by a `type="file"` input.
* [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#alt): A string. Specifies the alternative image text for a `type="image"` input.
* [`capture`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#capture): A string. Specifies the media (microphone, video, or camera) captured by a `type="file"` input.
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autocomplete): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values)
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autofocus): A boolean. If `true`, React will focus the element on mount.
* [`dirname`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#dirname): A string. Specifies the form field name for the element's directionality.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#disabled): A boolean. If `true`, the input will not be interactive and will appear dimmed.
* `children`: `<input>` does not accept children.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#form): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it's the closest parent form.
* [`formAction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formaction): A string. Overrides the parent `<form action>` for `type="submit"` and `type="image"`.
* [`formEnctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formenctype): A string. Overrides the parent `<form enctype>` for `type="submit"` and `type="image"`.
* [`formMethod`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formmethod): A string. Overrides the parent `<form method>` for `type="submit"` and `type="image"`.
* [`formNoValidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formnovalidate): A string. Overrides the parent `<form noValidate>` for `type="submit"` and `type="image"`.
* [`formTarget`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formtarget): A string. Overrides the parent `<form target>` for `type="submit"` and `type="image"`.
* [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#height): A string. Specifies the image height for `type="image"`.
* [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#list): A string. Specifies the `id` of the `<datalist>` with the autocomplete options.
* [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max): A number. Specifies the maximum value of numerical and datetime inputs.
* [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#maxlength): A number. Specifies the maximum length of text and other inputs.
* [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min): A number. Specifies the minimum value of numerical and datetime inputs.
* [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#minlength): A number. Specifies the minimum length of text and other inputs.
* [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#multiple): A boolean. Specifies whether multiple values are allowed for `<type="file"` and `type="email"`.
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#name): A string. Specifies the name for this input that's [submitted with the form.](#reading-the-input-values-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled inputs.](#controlling-an-input-with-a-state-variable) Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires after the selection inside the `<input>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
* `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`pattern`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern): A string. Specifies the pattern that the `value` must match.
* [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#placeholder): A string. Displayed in a dimmed color when the input value is empty.
* [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly): A boolean. If `true`, the input is not editable by the user.
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#required): A boolean. If `true`, the value must be provided for the form to submit.
* [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#size): A number. Similar to setting width, but the unit depends on the control.
* [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#src): A string. Specifies the image source for a `type="image"` input.
* [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step): A positive number or an `'any'` string. Specifies the distance between valid values.
* [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type): A string. One of the [input types.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types)
* [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#width): A string. Specifies the image width for a `type="image"` input.
#### Caveats {/*caveats*/}
- Checkboxes need `checked` (or `defaultChecked`), not `value` (or `defaultValue`).
- If a text input receives a string `value` prop, it will be [treated as controlled.](#controlling-an-input-with-a-state-variable)
- If a checkbox or a radio button receives a boolean `checked` prop, it will be [treated as controlled.](#controlling-an-input-with-a-state-variable)
- An input can't be both controlled and uncontrolled at the same time.
- An input cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled input needs an `onChange` event handler that synchronously updates its backing value.
---
## Usage {/*usage*/}
### Displaying inputs of different types {/*displaying-inputs-of-different-types*/}
@ -381,87 +462,6 @@ If there is no way to avoid re-rendering (for example, if `PageContent` depends
---
## Reference {/*reference*/}
### `<input>` {/*input*/}
To display an input, render the [built-in browser `<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) component.
```js
<input name="myInput" />
```
[See more examples above.](#usage)
#### Props {/*props*/}
`<input>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make an input controlled](#controlling-an-input-with-a-state-variable) by passing one of these props:
* [`checked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#checked): A boolean. For a checkbox input or a radio button, controls whether it is selected.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#value): A string. For a text input, controls its text. (For a radio button, specifies its form data.)
When you pass either of them, you must also pass an `onChange` handler that updates the passed value.
These `<input>` props are only relevant for uncontrolled inputs:
* [`defaultChecked`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#defaultChecked): A boolean. Specifies [the initial value](#providing-an-initial-value-for-an-input) for `type="checkbox"` and `type="radio"` inputs.
* [`defaultValue`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#defaultValue): A string. Specifies [the initial value](#providing-an-initial-value-for-an-input) for a text input.
These `<input>` props are relevant both for uncontrolled and controlled inputs:
* [`accept`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#accept): A string. Specifies which filetypes are accepted by a `type="file"` input.
* [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#alt): A string. Specifies the alternative image text for a `type="image"` input.
* [`capture`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#capture): A string. Specifies the media (microphone, video, or camera) captured by a `type="file"` input.
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autocomplete): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values)
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autofocus): A boolean. If `true`, React will focus the element on mount.
* [`dirname`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#dirname): A string. Specifies the form field name for the element's directionality.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#disabled): A boolean. If `true`, the input will not be interactive and will appear dimmed.
* `children`: `<input>` does not accept children.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#form): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it's the closest parent form.
* [`formAction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formaction): A string. Overrides the parent `<form action>` for `type="submit"` and `type="image"`.
* [`formEnctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formenctype): A string. Overrides the parent `<form enctype>` for `type="submit"` and `type="image"`.
* [`formMethod`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formmethod): A string. Overrides the parent `<form method>` for `type="submit"` and `type="image"`.
* [`formNoValidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formnovalidate): A string. Overrides the parent `<form noValidate>` for `type="submit"` and `type="image"`.
* [`formTarget`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formtarget): A string. Overrides the parent `<form target>` for `type="submit"` and `type="image"`.
* [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#height): A string. Specifies the image height for `type="image"`.
* [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#list): A string. Specifies the `id` of the `<datalist>` with the autocomplete options.
* [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max): A number. Specifies the maximum value of numerical and datetime inputs.
* [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#maxlength): A number. Specifies the maximum length of text and other inputs.
* [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min): A number. Specifies the minimum value of numerical and datetime inputs.
* [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#minlength): A number. Specifies the minimum length of text and other inputs.
* [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#multiple): A boolean. Specifies whether multiple values are allowed for `<type="file"` and `type="email"`.
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#name): A string. Specifies the name for this input that's [submitted with the form.](#reading-the-input-values-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled inputs.](#controlling-an-input-with-a-state-variable) Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires after the selection inside the `<input>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
* `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`pattern`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern): A string. Specifies the pattern that the `value` must match.
* [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#placeholder): A string. Displayed in a dimmed color when the input value is empty.
* [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly): A boolean. If `true`, the input is not editable by the user.
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#required): A boolean. If `true`, the value must be provided for the form to submit.
* [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#size): A number. Similar to setting width, but the unit depends on the control.
* [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#src): A string. Specifies the image source for a `type="image"` input.
* [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step): A positive number or an `'any'` string. Specifies the distance between valid values.
* [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type): A string. One of the [input types.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types)
* [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#width): A string. Specifies the image width for a `type="image"` input.
#### Caveats {/*caveats*/}
- Checkboxes need `checked` (or `defaultChecked`), not `value` (or `defaultValue`).
- If a text input receives a string `value` prop, it will be [treated as controlled.](#controlling-an-input-with-a-state-variable)
- If a checkbox or a radio button receives a boolean `checked` prop, it will be [treated as controlled.](#controlling-an-input-with-a-state-variable)
- An input can't be both controlled and uncontrolled at the same time.
- An input cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled input needs an `onChange` event handler that synchronously updates its backing value.
---
## Troubleshooting {/*troubleshooting*/}
### My text input doesn't update when I type into it {/*my-text-input-doesnt-update-when-i-type-into-it*/}

57
beta/src/content/apis/react-dom/components/option.md

@ -19,6 +19,35 @@ The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/
---
## Reference {/*reference*/}
### `<option>` {/*option*/}
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) lets you render an option inside a [`<select>`](/apis/react-dom/components/select) box.
```js
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
#### Props {/*props*/}
`<option>` supports all [common element props.](/apis/react-dom/components/common#props)
Additionally, `<option>` supports these props:
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#disabled): A boolean. If `true`, the option will not be selectable and will appear dimmed.
* [`label`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#label): A string. Specifies the meaning of the option. If not specified, the text inside the option is used.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#value): The value to be used [when submitting the parent `<select>` in a form](/apis/react-dom/components/select#reading-the-select-box-value-when-submitting-a-form) if this option is selected.
#### Caveats {/*caveats*/}
* React does not support the `selected` attribute on `<option>`. Instead, pass this option's `value` to the parent [`<select defaultValue>`](/apis/react-dom/components/select#providing-an-initially-selected-option) for an uncontrolled select box, or [`<select value>`](/apis/react-dom/components/select#controlling-a-select-box-with-a-state-variable) for a controlled select box.
---
## Usage {/*usage*/}
### Displaying a select box with options {/*displaying-a-select-box-with-options*/}
@ -50,31 +79,3 @@ select { margin: 5px; }
</Sandpack>
---
## Reference {/*reference*/}
### `<option>` {/*option*/}
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) lets you render an option inside a [`<select>`](/apis/react-dom/components/select) box.
```js
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
#### Props {/*props*/}
`<option>` supports all [common element props.](/apis/react-dom/components/common#props)
Additionally, `<option>` supports these props:
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#disabled): A boolean. If `true`, the option will not be selectable and will appear dimmed.
* [`label`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#label): A string. Specifies the meaning of the option. If not specified, the text inside the option is used.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#value): The value to be used [when submitting the parent `<select>` in a form](/apis/react-dom/components/select#reading-the-select-box-value-when-submitting-a-form) if this option is selected.
#### Caveats {/*caveats*/}
* React does not support the `selected` attribute on `<option>`. Instead, pass this option's `value` to the parent [`<select defaultValue>`](/apis/react-dom/components/select#providing-an-initially-selected-option) for an uncontrolled select box, or [`<select value>`](/apis/react-dom/components/select#controlling-a-select-box-with-a-state-variable) for a controlled select box.

43
beta/src/content/apis/react-dom/components/progress.md

@ -16,6 +16,27 @@ The [built-in browser `<progress>` component](https://developer.mozilla.org/en-U
---
## Reference {/*reference*/}
### `<progress>` {/*progress*/}
To display a progress indicator, render the [built-in browser `<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) component.
```js
<progress value={0.5} />
```
#### Props {/*props*/}
`<progress>` supports all [common element props.](/apis/react-dom/components/common#props)
Additionally, `<progress>` supports these props:
* [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress#attr-max): A number. Specifies the maximum `value`. Defaults to `1`.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress#attr-value): A number between `0` and `max`, or `null` for intermedinate progress. Specifies how much was done.
---
## Usage {/*usage*/}
### Controlling a progress indicator {/*controlling-a-progress-indicator*/}
@ -46,25 +67,3 @@ progress { display: block; }
```
</Sandpack>
---
## Reference {/*reference*/}
### `<progress>` {/*progress*/}
To display a progress indicator, render the [built-in browser `<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) component.
```js
<progress value={0.5} />
```
#### Props {/*props*/}
`<progress>` supports all [common element props.](/apis/react-dom/components/common#props)
Additionally, `<progress>` supports these props:
* [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress#attr-max): A number. Specifies the maximum `value`. Defaults to `1`.
* [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress#attr-value): A number between `0` and `max`, or `null` for intermedinate progress. Specifies how much was done.

115
beta/src/content/apis/react-dom/components/select.md

@ -19,6 +19,63 @@ The [built-in browser `<select>` component](https://developer.mozilla.org/en-US/
---
## Reference {/*reference*/}
### `<select>` {/*select*/}
To display a select box, render the [built-in browser `<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) component.
```js
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
[See more examples below.](#usage)
#### Props {/*props*/}
`<select>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make a select box controlled](#controlling-a-select-box-with-a-state-variable) by passing a `value` prop:
* `value`: A string (or an array of strings for [`multiple={true}`](#enabling-multiple-selection)). Controls which option is selected. Every value string match the `value` of some `<option>` nested inside the `<select>`.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<select>` is uncontrolled, you may pass the `defaultValue` prop instead:
* `defaultValue`: A string (or an array of strings for [`multiple={true}`](#enabling-multiple-selection)). Specifies [the initially selected option.](#providing-an-initially-selected-option)
These `<select>` props are relevant both for uncontrolled and controlled select boxs:
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-autocomplete): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values)
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-autofocus): A boolean. If `true`, React will focus the element on mount.
* `children`: `<select>` accepts [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option), [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup), and [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup) components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass your own components that eventually render `<option>` tags, each `<option>` you render must have a `value`.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-disabled): A boolean. If `true`, the select box will not be interactive and will appear dimmed.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-form): A string. Specifies the `id` of the `<form>` this select box belongs to. If omitted, it's the closest parent form.
* [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-multiple): A boolean. If `true`, the browser allows [multiple selection.](#enabling-multiple-selection)
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-name): A string. Specifies the name for this select box that's [submitted with the form.](#reading-the-select-box-value-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled select boxes.](#controlling-a-select-box-with-a-state-variable) Fires immediately when the user picks a different option. Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-required): A boolean. If `true`, the value must be provided for the form to submit.
* [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-size): A number. For `multiple={true}` selects, specifies the preferred number of initially visible items.
#### Caveats {/*caveats*/}
- Unlike in HTML, passing a `selected` attribute to `<option>` is not supported. Instead, use [`<select defaultValue>`](#providing-an-initially-selected-option) for uncontrolled select boxes and [`<select value>`](#controlling-a-select-box-with-a-state-variable) for controlled select boxes.
- If a select box receives a `value` prop, it will be [treated as controlled.](#controlling-a-select-box-with-a-state-variable)
- A select box can't be both controlled and uncontrolled at the same time.
- A select box cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled select box needs an `onChange` event handler that synchronously updates its backing value.
---
## Usage {/*usage*/}
### Displaying a select box with options {/*displaying-a-select-box-with-options*/}
@ -325,61 +382,3 @@ select { margin-bottom: 10px; display: block; }
Unlike in HTML, passing a `selected` attribute to an individual `<option>` is not supported.
</Pitfall>
<hr />
## Reference {/*reference*/}
### `<select>` {/*select*/}
To display a select box, render the [built-in browser `<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) component.
```js
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
```
[See more examples above.](#usage)
#### Props {/*props*/}
`<select>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make a select box controlled](#controlling-a-select-box-with-a-state-variable) by passing a `value` prop:
* `value`: A string (or an array of strings for [`multiple={true}`](#enabling-multiple-selection)). Controls which option is selected. Every value string match the `value` of some `<option>` nested inside the `<select>`.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<select>` is uncontrolled, you may pass the `defaultValue` prop instead:
* `defaultValue`: A string (or an array of strings for [`multiple={true}`](#enabling-multiple-selection)). Specifies [the initially selected option.](#providing-an-initially-selected-option)
These `<select>` props are relevant both for uncontrolled and controlled select boxs:
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-autocomplete): A string. Specifies one of the possible [autocomplete behaviors.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values)
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-autofocus): A boolean. If `true`, React will focus the element on mount.
* `children`: `<select>` accepts [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option), [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup), and [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup) components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass your own components that eventually render `<option>` tags, each `<option>` you render must have a `value`.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-disabled): A boolean. If `true`, the select box will not be interactive and will appear dimmed.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-form): A string. Specifies the `id` of the `<form>` this select box belongs to. If omitted, it's the closest parent form.
* [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-multiple): A boolean. If `true`, the browser allows [multiple selection.](#enabling-multiple-selection)
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-name): A string. Specifies the name for this select box that's [submitted with the form.](#reading-the-select-box-value-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled select boxes.](#controlling-a-select-box-with-a-state-variable) Fires immediately when the user picks a different option. Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-required): A boolean. If `true`, the value must be provided for the form to submit.
* [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#attr-size): A number. For `multiple={true}` selects, specifies the preferred number of initially visible items.
#### Caveats {/*caveats*/}
- Unlike in HTML, passing a `selected` attribute to `<option>` is not supported. Instead, use [`<select defaultValue>`](#providing-an-initially-selected-option) for uncontrolled select boxes and [`<select value>`](#controlling-a-select-box-with-a-state-variable) for controlled select boxes.
- If a select box receives a `value` prop, it will be [treated as controlled.](#controlling-a-select-box-with-a-state-variable)
- A select box can't be both controlled and uncontrolled at the same time.
- A select box cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled select box needs an `onChange` event handler that synchronously updates its backing value.

122
beta/src/content/apis/react-dom/components/textarea.md

@ -16,6 +16,67 @@ The [built-in browser `<textarea>` component](https://developer.mozilla.org/en-U
---
## Reference {/*reference*/}
### `<textarea>` {/*textarea*/}
To display a text area, render the [built-in browser `<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) component.
```js
<textarea name="postContent" />
```
[See more examples below.](#usage)
#### Props {/*props*/}
`<textarea>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make a text area controlled](#controlling-a-text-area-with-a-state-variable) by passing a `value` prop:
* `value`: A string. Controls the text inside the text area.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<textarea>` is uncontrolled, you may pass the `defaultValue` prop instead:
* `defaultValue`: A string. Specifies [the initial value](#providing-an-initial-value-for-a-text-area) for a text area.
These `<textarea>` props are relevant both for uncontrolled and controlled text areas:
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-autocomplete): Either `'on'` or `'off'`. Specifies the autocomplete behavior.
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-autofocus): A boolean. If `true`, React will focus the element on mount.
* `children`: `<textarea>` does not accept children. To set the initial value, use `defaultValue`.
* [`cols`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-cols): A number. Specifies the default width in average character widths. Defaults to `20`.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-disabled): A boolean. If `true`, the input will not be interactive and will appear dimmed.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-form): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it's the closest parent form.
* [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-maxlength): A number. Specifies the maximum length of text.
* [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-minlength): A number. Specifies the minimum length of text.
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#name): A string. Specifies the name for this input that's [submitted with the form.](#reading-the-textarea-value-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled text areas.](#controlling-a-text-area-with-a-state-variable) Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement/select_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires after the selection inside the `<textarea>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
* `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder): A string. Displayed in a dimmed color when the text area value is empty.
* [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-readonly): A boolean. If `true`, the text area is not editable by the user.
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-required): A boolean. If `true`, the value must be provided for the form to submit.
* [`rows`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-rows): A number. Specifies the default height in average character heights. Defaults to `2`.
* [`wrap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-wrap): Either `'hard'`, `'soft'`, or `'off'`. Specifies how the text should be wrapped when submitting a form.
#### Caveats {/*caveats*/}
- Passing children like `<textarea>something</textarea>` is not allowed. [Use `defaultValue` for initial content.](#providing-an-initial-value-for-a-text-area)
- If a text area receives a string `value` prop, it will be [treated as controlled.](#controlling-a-text-area-with-a-state-variable)
- A text area can't be both controlled and uncontrolled at the same time.
- A text area cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled text area needs an `onChange` event handler that synchronously updates its backing value.
---
## Usage {/*usage*/}
### Displaying a text area {/*displaying-a-text-area*/}
@ -275,67 +336,6 @@ textarea { display: block; margin-top: 5px; margin-bottom: 10px; }
---
## Reference {/*reference*/}
### `<textarea>` {/*textarea*/}
To display a text area, render the [built-in browser `<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) component.
```js
<textarea name="postContent" />
```
[See more examples above.](#usage)
#### Props {/*props*/}
`<textarea>` supports all [common element props.](/apis/react-dom/components/common#props)
You can [make a text area controlled](#controlling-a-text-area-with-a-state-variable) by passing a `value` prop:
* `value`: A string. Controls the text inside the text area.
When you pass `value`, you must also pass an `onChange` handler that updates the passed value.
If your `<textarea>` is uncontrolled, you may pass the `defaultValue` prop instead:
* `defaultValue`: A string. Specifies [the initial value](#providing-an-initial-value-for-a-text-area) for a text area.
These `<textarea>` props are relevant both for uncontrolled and controlled text areas:
* [`autoComplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-autocomplete): Either `'on'` or `'off'`. Specifies the autocomplete behavior.
* [`autoFocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-autofocus): A boolean. If `true`, React will focus the element on mount.
* `children`: `<textarea>` does not accept children. To set the initial value, use `defaultValue`.
* [`cols`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-cols): A number. Specifies the default width in average character widths. Defaults to `20`.
* [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-disabled): A boolean. If `true`, the input will not be interactive and will appear dimmed.
* [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-form): A string. Specifies the `id` of the `<form>` this input belongs to. If omitted, it's the closest parent form.
* [`maxLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-maxlength): A number. Specifies the maximum length of text.
* [`minLength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-minlength): A number. Specifies the minimum length of text.
* [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#name): A string. Specifies the name for this input that's [submitted with the form.](#reading-the-textarea-value-when-submitting-a-form)
* `onChange`: An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Required for [controlled text areas.](#controlling-a-text-area-with-a-state-variable) Fires immediately when the input's value is changed by the user (for example, it fires on every keystroke). Behaves like the browser [`input` event.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
* `onChangeCapture`: A version of `onChange` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to use `onChange` instead which works similarly.
* `onInputCapture`: A version of `onInput` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires if an input fails validation on form submit. Unlike the built-in `invalid` event, the React `onInvalid` event bubbles.
* `onInvalidCapture`: A version of `onInvalid` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement/select_event): An [`Event` handler](/apis/react-dom/components/common#event-handler) function. Fires after the selection inside the `<textarea>` changes. React extends the `onSelect` event to also fire for empty selection and on edits (which may affect the selection).
* `onSelectCapture`: A version of `onSelect` that fires in the [capture phase.](/learn/responding-to-events#capture-phase-events)
* [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder): A string. Displayed in a dimmed color when the text area value is empty.
* [`readOnly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-readonly): A boolean. If `true`, the text area is not editable by the user.
* [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-required): A boolean. If `true`, the value must be provided for the form to submit.
* [`rows`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-rows): A number. Specifies the default height in average character heights. Defaults to `2`.
* [`wrap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-wrap): Either `'hard'`, `'soft'`, or `'off'`. Specifies how the text should be wrapped when submitting a form.
#### Caveats {/*caveats*/}
- Passing children like `<textarea>something</textarea>` is not allowed. [Use `defaultValue` for initial content.](#providing-an-initial-value-for-a-text-area)
- If a text area receives a string `value` prop, it will be [treated as controlled.](#controlling-a-text-area-with-a-state-variable)
- A text area can't be both controlled and uncontrolled at the same time.
- A text area cannot switch between being controlled or uncontrolled over its lifetime.
- Every controlled text area needs an `onChange` event handler that synchronously updates its backing value.
---
## Troubleshooting {/*troubleshooting*/}
### My text area doesn't update when I type into it {/*my-text-area-doesnt-update-when-i-type-into-it*/}

81
beta/src/content/apis/react-dom/createPortal.md

@ -20,6 +20,46 @@ title: createPortal
---
## Reference {/*reference*/}
### `createPortal(children, domNode)` {/*createportal*/}
To create a portal, call `createPortal`, passing some JSX, and the DOM node where it should be rendered:
```js
import { createPortal } from 'react-dom';
// ...
<div>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body
)}
</div>
```
[See more examples below.](#usage)
A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events still bubble up from children to parents according to the React tree.
#### Parameters {/*parameters*/}
* `children`: Anything that can be rendered with React, such as a piece of JSX (e.g. `<div />` or `<SomeComponent />`), a [Fragment](/apis/react/Fragment) (`<>...</>`), a string or a number, or an array of these.
* `domNode`: Some DOM node, such as those returned by `document.getElementById()`. The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated.
#### Returns {/*returns*/}
`createPortal` returns a React node that can be included into JSX or returned from a React component. If React encounters it in the render output, it will place the provided `children` inside the provided `domNode`.
#### Caveats {/*caveats*/}
* Events from portals propagate according to the React tree rather than the DOM tree. For example, if you click inside a portal, and the portal is wrapped in `<div onClick>`, that `onClick` handler will fire. If this causes issues, either stop the event propagation from inside the portal, or move the portal itself up in the React tree.
---
## Usage {/*usage*/}
### Rendering to a different part of the DOM {/*rendering-to-a-different-part-of-the-dom*/}
@ -415,44 +455,3 @@ button { margin: 5px; }
```
</Sandpack>
---
## Reference {/*reference*/}
### `createPortal(children, domNode)` {/*createportal*/}
To create a portal, call `createPortal`, passing some JSX, and the DOM node where it should be rendered:
```js
import { createPortal } from 'react-dom';
// ...
<div>
<p>This child is placed in the parent div.</p>
{createPortal(
<p>This child is placed in the document body.</p>,
document.body
)}
</div>
```
[See more examples.](#usage)
A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events still bubble up from children to parents according to the React tree.
#### Parameters {/*parameters*/}
* `children`: Anything that can be rendered with React, such as a piece of JSX (e.g. `<div />` or `<SomeComponent />`), a [Fragment](/apis/react/Fragment) (`<>...</>`), a string or a number, or an array of these.
* `domNode`: Some DOM node, such as those returned by `document.getElementById()`. The node must already exist. Passing a different DOM node during an update will cause the portal content to be recreated.
#### Returns {/*returns*/}
`createPortal` returns a React node that can be included into JSX or returned from a React component. If React encounters it in the render output, it will place the provided `children` inside the provided `domNode`.
#### Caveats {/*caveats*/}
* Events from portals propagate according to the React tree rather than the DOM tree. For example, if you click inside a portal, and the portal is wrapped in `<div onClick>`, that `onClick` handler will fire. If this causes issues, either stop the event propagation from inside the portal, or move the portal itself up in the React tree.

78
beta/src/content/apis/react-dom/findDOMNode.md

@ -22,6 +22,45 @@ const domNode = findDOMNode(componentInstance)
---
## Reference {/*reference*/}
### `findDOMNode(componentInstance)` {/*finddomnode*/}
<Deprecated>
This API will be removed in a future major version of React. [See the alternatives.](#alternatives)
</Deprecated>
Call `findDOMNode` to find the browser DOM node for a given React [class component](/apis/react/Component) instance.
```js
const domNode = findDOMNode(componentInstance);
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `componentInstance`: An instance of the [`Component`](/apis/react/Component) subclass. For example, `this` inside a class component.
#### Returns {/*returns*/}
`findDOMNode` returns the first closest browser DOM node within the given `componentInstance`. When a component renders to `null`, or renders `false`, `findDOMNode` returns `null`. When a component renders to a string, `findDOMNode` returns a text DOM node containing that value.
#### Caveats {/*caveats*/}
* A component may return an array or a [Fragment](/apis/react/Fragment) with multiple children. In that case `findDOMNode`, will return the DOM node corresponding to the first non-empty child.
* `findDOMNode` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created), an exception will be thrown.
* `findDOMNode` only returns the result at the time of your call. If a child component renders a different node later, there is no way for you to be notified of this change.
* `findDOMNode` accepts a class component instance, so it can't be used with function components.
---
## Usage {/*usage*/}
### Finding the root DOM node of a class component {/*finding-the-root-dom-node-of-a-class-component*/}
@ -404,42 +443,3 @@ There is currently no direct equivalent for this use case, which is why `findDOM
```
This also applies to focusing and scrolling to arbitrary children.
---
## Reference {/*reference*/}
### `findDOMNode(componentInstance)` {/*finddomnode*/}
<Deprecated>
This API will be removed in a future major version of React. [See the alternatives.](#alternatives)
</Deprecated>
Call `findDOMNode` to find the browser DOM node for a given React [class component](/apis/react/Component) instance.
```js
const domNode = findDOMNode(componentInstance);
```
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `componentInstance`: An instance of the [`Component`](/apis/react/Component) subclass. For example, `this` inside a class component.
#### Returns {/*returns*/}
`findDOMNode` returns the first closest browser DOM node within the given `componentInstance`. When a component renders to `null`, or renders `false`, `findDOMNode` returns `null`. When a component renders to a string, `findDOMNode` returns a text DOM node containing that value.
#### Caveats {/*caveats*/}
* A component may return an array or a [Fragment](/apis/react/Fragment) with multiple children. In that case `findDOMNode`, will return the DOM node corresponding to the first non-empty child.
* `findDOMNode` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created), an exception will be thrown.
* `findDOMNode` only returns the result at the time of your call. If a child component renders a different node later, there is no way for you to be notified of this change.
* `findDOMNode` accepts a class component instance, so it can't be used with function components.

68
beta/src/content/apis/react-dom/flushSync.md

@ -22,6 +22,40 @@ flushSync(callback)
---
## Reference {/*reference*/}
### `flushSync(callback)` {/*create-root*/}
Call `flushSync` to force React to flush any pending work and update the DOM synchronously.
```js
flushSync(() => {
setState(true);
});
```
Most of the time, `flushSync` can be avoided. Use `flushSync` as last resort.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `callback`: A function. React will immediately call this callback and flush any updates it contains synchronously. It may also flush any pending updates, or Effects, or updates inside of Effects. If an update suspends as a result of this `flushSync` call, the fallbacks may be re-shown.
#### Returns {/*returns*/}
`flushSync` returns `undefined`.
#### Caveats {/*caveats*/}
* `flushSync` can significantly hurt performance. Use sparingly.
* `flushSync` may force pending Suspense boundaries to show their `fallback` state.
* `flushSync` may run pending effects and synchronously apply any updates they contain before returning.
* `flushSync` may flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.
---
## Usage {/*usage*/}
### Flushing updates for third-party integrations {/*flushing-updates-for-third-party-integrations*/}
@ -97,37 +131,3 @@ If you remove the call to `flushSync`, then when the print dialog will display `
Most of the time, `flushSync` can be avoided, so use `flushSync` as last resort.
</Pitfall>
---
## Reference {/*reference*/}
### `flushSync(callback)` {/*create-root*/}
Call `flushSync` to force React to flush any pending work and update the DOM synchronously.
```js
flushSync(() => {
setState(true);
});
```
Most of the time, `flushSync` can be avoided. Use `flushSync` as last resort.
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `callback`: A function. React will immediately call this callback and flush any updates it contains synchronously. It may also flush any pending updates, or Effects, or updates inside of Effects. If an update suspends as a result of this `flushSync` call, the fallbacks may be re-shown.
#### Returns {/*returns*/}
`flushSync` returns `undefined`.
#### Caveats {/*caveats*/}
* `flushSync` can significantly hurt performance. Use sparingly.
* `flushSync` may force pending Suspense boundaries to show their `fallback` state.
* `flushSync` may run pending effects and synchronously apply any updates they contain before returning.
* `flushSync` may flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.

86
beta/src/content/apis/react-dom/hydrate.md

@ -24,6 +24,48 @@ hydrate(reactNode, domNode, callback?)
---
## Reference {/*reference*/}
### `hydrate(reactNode, domNode, callback?)` {/*hydrate*/}
<Deprecated>
In React 18, `hydrate` was replaced by [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Using `hydrate` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
This API will be removed in a future major version of React.
</Deprecated>
Call `hydrate` in React 17 and below to “attach” React to existing HTML that was already rendered by React in a server environment.
```js
hydrate(reactNode, domNode);
```
React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrate` call with its root component.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToString(<App />)` in React 17.
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
* **optional**: `callback`: A function. If passed, React will call it after your component is hydrated.
#### Returns {/*returns*/}
`hydrate` returns null.
#### Caveats {/*caveats*/}
* `hydrate` expects the rendered content to be identical with the server-rendered content. React can patch up differences in text content, but you should treat mismatches as bugs and fix them.
* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
* You'll likely have only one `hydrate` call in your app. If you use a framework, it might do this call for you.
* If your app is client-rendered with no HTML rendered already, using `hydrate()` is not supported. Use [render()](/apis/react-dom/render) (for React 17 and below) or [createRoot()](/apis/react-dom/client/createRoot) (for React 18+) instead.
---
## Usage {/*usage*/}
Call `hydrate` to attach a <CodeStep step={1}>React component</CodeStep> into a server-rendered <CodeStep step={2}>browser DOM node</CodeStep>.
@ -163,47 +205,3 @@ This way the initial render pass will render the same content as the server, avo
This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user.
</Pitfall>
---
## Reference {/*reference*/}
### `hydrate(reactNode, domNode, callback?)` {/*hydrate*/}
<Deprecated>
In React 18, `hydrate` was replaced by [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Using `hydrate` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
This API will be removed in a future major version of React.
</Deprecated>
Call `hydrate` in React 17 and below to “attach” React to existing HTML that was already rendered by React in a server environment.
```js
hydrate(reactNode, domNode);
```
React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrate` call with its root component.
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToString(<App />)` in React 17.
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
* **optional**: `callback`: A function. If passed, React will call it after your component is hydrated.
#### Returns {/*returns*/}
`hydrate` returns null.
#### Caveats {/*caveats*/}
* `hydrate` expects the rendered content to be identical with the server-rendered content. React can patch up differences in text content, but you should treat mismatches as bugs and fix them.
* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
* You'll likely have only one `hydrate` call in your app. If you use a framework, it might do this call for you.
* If your app is client-rendered with no HTML rendered already, using `hydrate()` is not supported. Use [render()](/apis/react-dom/render) (for React 17 and below) or [createRoot()](/apis/react-dom/client/createRoot) (for React 18+) instead.
---

102
beta/src/content/apis/react-dom/render.md

@ -24,6 +24,56 @@ render(reactNode, domNode, callback?)
---
## Reference {/*reference*/}
### `render(reactNode, domNode, callback?)` {/*render*/}
<Deprecated>
In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Using `render` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
This API will be removed in a future major version of React.
</Deprecated>
Call `render` to display a React component inside a browser DOM element.
```js
const domNode = document.getElementById('root');
render(<App />, domNode);
```
React will display `<App />` in the `domNode`, and take over managing the DOM inside it.
An app fully built with React will usually only have one `render` call with its root component. A page that uses "sprinkles" of React for parts of the page may have as many `render` calls as needed.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will display the `reactNode` you pass inside this DOM element. From this moment, React will manage the DOM inside the `domNode` and update it when your React tree changes.
* **optional** `callback`: A function. If passed, React will call it after your component is placed into the DOM.
#### Returns {/*returns*/}
`render` usually returns `null`. However, if the `reactNode` you pass is a *class component*, then it will return an instance of that component.
#### Caveats {/*caveats*/}
* In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Please use `createRoot` for React 18 and beyond.
* The first time you call `render`, React will clear all the existing HTML content inside the `domNode` before rendering the React component into it. If your `domNode` contains HTML generated by React on the server or during the build, use [`hydrate()`](/apis/react-dom/hydrate) instead, which attaches the event handlers to the existing HTML.
* If you call `render` on the same `domNode` more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same `domNode` again is similar to calling the [`set` function](/apis/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.
* If your app is fully built with React, you'll likely have only one `render` call in your app. (If you use a framework, it might do this call for you.) When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use [`createPortal`](/apis/react-dom/createPortal) instead of `render`.
---
## Usage {/*usage*/}
Call `render` to display a <CodeStep step={1}>React component</CodeStep> inside a <CodeStep step={2}>browser DOM node</CodeStep>.
@ -172,55 +222,3 @@ export default function App({counter}) {
</Sandpack>
It is uncommon to call `render` multiple times. Usually, you'll [update state](/apis/react/useState) inside one of the components instead.
---
## Reference {/*reference*/}
### `render(reactNode, domNode, callback?)` {/*render*/}
<Deprecated>
In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Using `render` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
This API will be removed in a future major version of React.
</Deprecated>
Call `render` to display a React component inside a browser DOM element.
```js
const domNode = document.getElementById('root');
render(<App />, domNode);
```
React will display `<App />` in the `domNode`, and take over managing the DOM inside it.
An app fully built with React will usually only have one `render` call with its root component. A page that uses "sprinkles" of React for parts of the page may have as many `render` calls as needed.
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will display the `reactNode` you pass inside this DOM element. From this moment, React will manage the DOM inside the `domNode` and update it when your React tree changes.
* **optional** `callback`: A function. If passed, React will call it after your component is placed into the DOM.
#### Returns {/*returns*/}
`render` usually returns `null`. However, if the `reactNode` you pass is a *class component*, then it will return an instance of that component.
#### Caveats {/*caveats*/}
* In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Please use `createRoot` for React 18 and beyond.
* The first time you call `render`, React will clear all the existing HTML content inside the `domNode` before rendering the React component into it. If your `domNode` contains HTML generated by React on the server or during the build, use [`hydrate()`](/apis/react-dom/hydrate) instead, which attaches the event handlers to the existing HTML.
* If you call `render` on the same `domNode` more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same `domNode` again is similar to calling the [`set` function](/apis/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.
* If your app is fully built with React, you'll likely have only one `render` call in your app. (If you use a framework, it might do this call for you.) When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use [`createPortal`](/apis/react-dom/createPortal) instead of `render`.
---

51
beta/src/content/apis/react-dom/server/renderToNodeStream.md

@ -22,32 +22,6 @@ const stream = renderToNodeStream(reactNode)
---
## Usage {/*usage*/}
### Rendering a React tree as HTML to a Node.js Readable Stream {/*rendering-a-react-tree-as-html-to-a-nodejs-readable-stream*/}
<Deprecated>
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
</Deprecated>
Call `renderToNodeStream` to get a [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams) which you can pipe to your server response:
```js {5-6}
import { renderToNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToNodeStream(<App />);
stream.pipe(response);
});
```
The stream will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.
---
## Reference {/*reference*/}
### `renderToNodeStream(reactNode)` {/*rendertonodestream*/}
@ -83,3 +57,28 @@ A [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams)
* The returned stream is a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.
---
## Usage {/*usage*/}
### Rendering a React tree as HTML to a Node.js Readable Stream {/*rendering-a-react-tree-as-html-to-a-nodejs-readable-stream*/}
<Deprecated>
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
</Deprecated>
Call `renderToNodeStream` to get a [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams) which you can pipe to your server response:
```js {5-6}
import { renderToNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToNodeStream(<App />);
stream.pipe(response);
});
```
The stream will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.

94
beta/src/content/apis/react-dom/server/renderToPipeableStream.md

@ -22,6 +22,53 @@ This API is specific to Node.js. Environments with [Web Streams,](https://develo
---
## Reference {/*reference*/}
### `renderToPipeableStream(reactNode, options)` {/*rendertopipeablestream*/}
Call `renderToPipeableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams)
```js
import { renderToPipeableStream } from 'react-dom/server';
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
* **optional** `options`: An object with streaming options.
* **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
* **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Omit it if you don't want to run React on the client at all.
* **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot#parameters)
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
* **optional** `onAllReady`: A callback that fires when all rendering is complete, including both the [shell](#specifying-what-goes-into-the-shell) and all additional [content.](#streaming-more-content-as-it-loads) You can use this instead of `onShellReady` [for crawlers and static generation.](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) If you start streaming here, you won't get any progressive loading. The stream will contain the final HTML.
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](#recovering-from-errors-outside-the-shell) or [not.](#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](#setting-the-status-code) before the shell is emitted.
* **optional** `onShellReady`: A callback that fires right after the [initial shell](#specifying-what-goes-into-the-shell) has been rendered. You can [set the status code](#setting-the-status-code) and call `pipe` here to start streaming. React will [stream the additional content](#streaming-more-content-as-it-loads) after the shell along with the inline `<script>` tags that place that replace the HTML loading fallbacks with the content.
* **optional** `onShellError`: A callback that fires if there was an error rendering the initial shell. It receives the error as an argument. No bytes were emitted from the stream yet, and neither `onShellReady` nor `onAllReady` will get called, so you can [output a fallback HTML shell.](#recovering-from-errors-inside-the-shell)
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
#### Returns {/*returns*/}
`renderToPipeableStream` returns an object with two methods:
* `pipe` outputs the HTML into the provided [Writable Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams) Call `pipe` in `onShellReady` if you want to enable streaming, or in `onAllReady` for crawlers and static generation.
* `abort` lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client.
---
## Usage {/*usage*/}
### Rendering a React tree as HTML to a Node.js Stream {/*rendering-a-react-tree-as-html-to-a-nodejs-stream*/}
@ -554,50 +601,3 @@ setTimeout(() => {
```
React will flush the remaining loading fallbacks as HTML, and will attempt to render the rest on the client.
---
## Reference {/*reference*/}
### `renderToPipeableStream(reactNode, options)` {/*rendertopipeablestream*/}
Call `renderToPipeableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams)
```js
import { renderToPipeableStream } from 'react-dom/server';
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
response.setHeader('content-type', 'text/html');
pipe(response);
}
});
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
* **optional** `options`: An object with streaming options.
* **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
* **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Omit it if you don't want to run React on the client at all.
* **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot#parameters)
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
* **optional** `onAllReady`: A callback that fires when all rendering is complete, including both the [shell](#specifying-what-goes-into-the-shell) and all additional [content.](#streaming-more-content-as-it-loads) You can use this instead of `onShellReady` [for crawlers and static generation.](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) If you start streaming here, you won't get any progressive loading. The stream will contain the final HTML.
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](#recovering-from-errors-outside-the-shell) or [not.](#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](#setting-the-status-code) before the shell is emitted.
* **optional** `onShellReady`: A callback that fires right after the [initial shell](#specifying-what-goes-into-the-shell) has been rendered. You can [set the status code](#setting-the-status-code) and call `pipe` here to start streaming. React will [stream the additional content](#streaming-more-content-as-it-loads) after the shell along with the inline `<script>` tags that place that replace the HTML loading fallbacks with the content.
* **optional** `onShellError`: A callback that fires if there was an error rendering the initial shell. It receives the error as an argument. No bytes were emitted from the stream yet, and neither `onShellReady` nor `onAllReady` will get called, so you can [output a fallback HTML shell.](#recovering-from-errors-inside-the-shell)
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
#### Returns {/*returns*/}
`renderToPipeableStream` returns an object with two methods:
* `pipe` outputs the HTML into the provided [Writable Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams) Call `pipe` in `onShellReady` if you want to enable streaming, or in `onAllReady` for crawlers and static generation.
* `abort` lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client.

100
beta/src/content/apis/react-dom/server/renderToReadableStream.md

@ -22,6 +22,56 @@ This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/
---
## Reference {/*reference*/}
### `renderToReadableStream(reactNode, options?)` {/*rendertoreadablestream*/}
Call `renderToReadableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams)
```js
import { renderToReadableStream } from 'react-dom/server';
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
* **optional** `options`: An object with streaming options.
* **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
* **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Omit it if you don't want to run React on the client at all.
* **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot#parameters)
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](#recovering-from-errors-outside-the-shell) or [not.](#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](#setting-the-status-code) before the shell is emitted.
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
* **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client.
#### Returns {/*returns*/}
`renderToReadableStream` returns a Promise:
- If rendering the [shell](#specifying-what-goes-into-the-shell) is successful, that Promise will resolve to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
- If rendering the shell fails, the Promise will be rejected. [Use this to output a fallback shell.](#recovering-from-errors-inside-the-shell)
The returned stream has an additional property:
* `allReady`: A Promise that resolves when all rendering is complete, including both the [shell](#specifying-what-goes-into-the-shell) and all additional [content.](#streaming-more-content-as-it-loads) You can `await stream.allReady` before returning a response [for crawlers and static generation.](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) If you do that, you won't get any progressive loading. The stream will contain the final HTML.
---
## Usage {/*usage*/}
### Rendering a React tree as HTML to a Readable Web Stream {/*rendering-a-react-tree-as-html-to-a-readable-web-stream*/}
@ -567,53 +617,3 @@ async function handler(request) {
```
React will flush the remaining loading fallbacks as HTML, and will attempt to render the rest on the client.
---
## Reference {/*reference*/}
### `renderToReadableStream(reactNode, options?)` {/*rendertoreadablestream*/}
Call `renderToReadableStream` to render your React tree as HTML into a [Node.js Stream.](https://nodejs.org/api/stream.html#writable-streams)
```js
import { renderToReadableStream } from 'react-dom/server';
async function handler(request) {
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js']
});
return new Response(stream, {
headers: { 'content-type': 'text/html' },
});
}
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX element like `<App />`. It is expected to represent the entire document, so the `App` component should render the `<html>` tag.
* **optional** `options`: An object with streaming options.
* **optional** `bootstrapScriptContent`: If specified, this string will be placed in an inline `<script>` tag.
* **optional** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Omit it if you don't want to run React on the client at all.
* **optional** `bootstrapModules`: Like `bootstrapScripts`, but emits [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) instead.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot#parameters)
* **optional** `namespaceURI`: A string with the root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris) for the stream. Defaults to regular HTML. Pass `'http://www.w3.org/2000/svg'` for SVG or `'http://www.w3.org/1998/Math/MathML'` for MathML.
* **optional** `nonce`: A [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string to allow scripts for [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
* **optional** `onError`: A callback that fires whenever there is a server error, whether [recoverable](#recovering-from-errors-outside-the-shell) or [not.](#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](#logging-crashes-on-the-server) make sure that you still call `console.error`. You can also use it to [adjust the status code](#setting-the-status-code) before the shell is emitted.
* **optional** `progressiveChunkSize`: The number of bytes in a chunk. [Read more about the default heuristic.](https://github.com/facebook/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
* **optional** `signal`: An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client.
#### Returns {/*returns*/}
`renderToReadableStream` returns a Promise:
- If rendering the [shell](#specifying-what-goes-into-the-shell) is successful, that Promise will resolve to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
- If rendering the shell fails, the Promise will be rejected. [Use this to output a fallback shell.](#recovering-from-errors-inside-the-shell)
The returned stream has an additional property:
* `allReady`: A Promise that resolves when all rendering is complete, including both the [shell](#specifying-what-goes-into-the-shell) and all additional [content.](#streaming-more-content-as-it-loads) You can `await stream.allReady` before returning a response [for crawlers and static generation.](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) If you do that, you won't get any progressive loading. The stream will contain the final HTML.

55
beta/src/content/apis/react-dom/server/renderToStaticMarkup.md

@ -16,34 +16,6 @@ const html = renderToStaticMarkup(reactNode)
---
## Usage {/*usage*/}
### Rendering a non-interactive React tree as HTML to a string {/*rendering-a-non-interactive-react-tree-as-html-to-a-string*/}
Call `renderToStaticMarkup` to render your app to an HTML string which you can send with your server response:
```js {5-6}
import { renderToStaticMarkup } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const html = renderToStaticMarkup(<Page />);
response.send(html);
});
```
This will produce the initial non-interactive HTML output of your React components.
<Pitfall>
This method renders **non-interactive HTML that cannot be hydrated.** This is useful if you want to use React as a simple static page generator, or if you're rendering completely static content like emails.
Interactive apps should use [`renderToString`](/apis/react-dom/server/renderToString) on the server and [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) on the client.
</Pitfall>
---
## Reference {/*reference*/}
### `renderToStaticMarkup(reactNode)` {/*rendertostaticmarkup*/}
@ -72,3 +44,30 @@ An HTML string.
* `renderToStaticMarkup` works in the browser, but using it in the client code is not recommended. If you need to render a component to HTML in the browser, [get the HTML by rendering it into a DOM node.](/apis/react-dom/server/renderToString#removing-rendertostring-from-the-client-code)
---
## Usage {/*usage*/}
### Rendering a non-interactive React tree as HTML to a string {/*rendering-a-non-interactive-react-tree-as-html-to-a-string*/}
Call `renderToStaticMarkup` to render your app to an HTML string which you can send with your server response:
```js {5-6}
import { renderToStaticMarkup } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const html = renderToStaticMarkup(<Page />);
response.send(html);
});
```
This will produce the initial non-interactive HTML output of your React components.
<Pitfall>
This method renders **non-interactive HTML that cannot be hydrated.** This is useful if you want to use React as a simple static page generator, or if you're rendering completely static content like emails.
Interactive apps should use [`renderToString`](/apis/react-dom/server/renderToString) on the server and [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) on the client.
</Pitfall>

56
beta/src/content/apis/react-dom/server/renderToStaticNodeStream.md

@ -16,34 +16,6 @@ const stream = renderToStaticNodeStream(reactNode)
---
## Usage {/*usage*/}
### Rendering a React tree as static HTML to a Node.js Readable Stream {/*rendering-a-react-tree-as-static-html-to-a-nodejs-readable-stream*/}
Call `renderToStaticNodeStream` to get a [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams) which you can pipe to your server response:
```js {5-6}
import { renderToStaticNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToStaticNodeStream(<Page />);
stream.pipe(response);
});
```
The stream will produce the initial non-interactive HTML output of your React components.
<Pitfall>
This method renders **non-interactive HTML that cannot be hydrated.** This is useful if you want to use React as a simple static page generator, or if you're rendering completely static content like emails.
Interactive apps should use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) on the server and [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) on the client.
</Pitfall>
---
## Reference {/*reference*/}
### `renderToStaticNodeStream(reactNode)` {/*rendertostaticnodestream*/}
@ -75,3 +47,31 @@ A [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams)
* The returned stream is a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like [iconv-lite](https://www.npmjs.com/package/iconv-lite), which provides transform streams for transcoding text.
## Usage {/*usage*/}
### Rendering a React tree as static HTML to a Node.js Readable Stream {/*rendering-a-react-tree-as-static-html-to-a-nodejs-readable-stream*/}
Call `renderToStaticNodeStream` to get a [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams) which you can pipe to your server response:
```js {5-6}
import { renderToStaticNodeStream } from 'react-dom/server';
// The route handler syntax depends on your backend framework
app.use('/', (request, response) => {
const stream = renderToStaticNodeStream(<Page />);
stream.pipe(response);
});
```
The stream will produce the initial non-interactive HTML output of your React components.
<Pitfall>
This method renders **non-interactive HTML that cannot be hydrated.** This is useful if you want to use React as a simple static page generator, or if you're rendering completely static content like emails.
Interactive apps should use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) on the server and [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) on the client.
</Pitfall>
---

57
beta/src/content/apis/react-dom/server/renderToString.md

@ -22,6 +22,34 @@ const html = renderToString(reactNode)
---
## Reference {/*reference*/}
### `renderToString(reactNode)` {/*rendertostring*/}
On the server, call `renderToString` to render your app to HTML.
```js {3-4}
const html = renderToString(<App />);
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX node like `<App />`.
#### Returns {/*returns*/}
An HTML string.
#### Caveats {/*caveats*/}
* `renderToString` has limited Suspense support. If a component suspends, `renderToString` immediately sends its fallback as HTML.
* `renderToString` works in the browser, but using it in the client code is [not recommended.](#removing-rendertostring-from-the-client-code)
---
## Usage {/*usage*/}
### Rendering a React tree as HTML to a string {/*rendering-a-react-tree-as-html-to-a-string*/}
@ -92,35 +120,6 @@ console.log(div.innerHTML); // For example, "<svg>...</svg>"
The [`flushSync`](/apis/react-dom/flushSync) call is necessary so that the DOM is updated before reading its [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property.
---
## Reference {/*reference*/}
### `renderToString(reactNode)` {/*rendertostring*/}
On the server, call `renderToString` to render your app to HTML.
```js {3-4}
const html = renderToString(<App />);
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
* `reactNode`: A React node you want to render to HTML. For example, a JSX node like `<App />`.
#### Returns {/*returns*/}
An HTML string.
#### Caveats {/*caveats*/}
* `renderToString` has limited Suspense support. If a component suspends, `renderToString` immediately sends its fallback as HTML.
* `renderToString` works in the browser, but using it in the client code is [not recommended.](#removing-rendertostring-from-the-client-code)
---
## Troubleshooting {/*troubleshooting*/}

66
beta/src/content/apis/react-dom/unmountComponentAtNode.md

@ -24,6 +24,39 @@ unmountComponentAtNode(domNode)
---
## Reference {/*reference*/}
### `unmountComponentAtNode(domNode)` {/*unmountcomponentatnode*/}
<Deprecated>
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/apis/react-dom/client/createRoot#root-unmount).
This API will be removed in a future major version of React.
</Deprecated>
Call `unmountComponentAtNode` to remove a mounted React component from the DOM and clean up its event handlers and state.
```js
const domNode = document.getElementById('root');
render(<App />, domNode);
unmountComponentAtNode(domNode);
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will remove a mounted React component from this element.
#### Returns {/*returns*/}
`unmountComponentAtNode` returns `true` if a component was unmounted and `false` otherwise.
---
## Usage {/*usage*/}
Call `unmountComponentAtNode` to remove a <CodeStep step={1}>mounted React component</CodeStep> from a <CodeStep step={2}>browser DOM node</CodeStep> and clean up its event handlers and state.
@ -84,36 +117,3 @@ export default function App() {
```
</Sandpack>
---
## Reference {/*reference*/}
### `unmountComponentAtNode(domNode)` {/*unmountcomponentatnode*/}
<Deprecated>
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/apis/react-dom/client/createRoot#root-unmount).
This API will be removed in a future major version of React.
</Deprecated>
Call `unmountComponentAtNode` to remove a mounted React component from the DOM and clean up its event handlers and state.
```js
const domNode = document.getElementById('root');
render(<App />, domNode);
unmountComponentAtNode(domNode);
```
[See examples above.](#usage)
#### Parameters {/*parameters*/}
* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will remove a mounted React component from this element.
#### Returns {/*returns*/}
`unmountComponentAtNode` returns `true` if a component was unmounted and `false` otherwise.

330
beta/src/content/apis/react/Children.md

@ -27,6 +27,171 @@ const mappedChildren = Children.map(children, child =>
---
## Reference {/*reference*/}
### `Children.count(children)` {/*children-count*/}
Call `Children.count(children)` to count the number of children in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function RowList({ children }) {
return (
<>
<h1>Total rows: {Children.count(children)}</h1>
...
</>
);
}
```
[See more examples below.](#counting-children)
#### Parameters {/*children-count-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-count-returns*/}
The number of nodes inside these `children`.
#### Caveats {/*children-count-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
---
### `Children.forEach(children, fn, thisArg?)` {/*children-foreach*/}
Call `Children.forEach(children, fn, thisArg?)` to run some code for each child in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function SeparatorList({ children }) {
const result = [];
Children.forEach(children, (child, index) => {
result.push(child);
result.push(<hr key={index} />);
});
// ...
```
[See more examples below.](#running-some-code-for-each-child)
#### Parameters {/*children-foreach-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
* `fn`: The function you want to run for each child, similar to the [array `forEach` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call.
* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`.
#### Returns {/*children-foreach-returns*/}
`Children.forEach` returns `undefined`.
#### Caveats {/*children-foreach-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
---
### `Children.map(children, fn, thisArg?)` {/*children-map*/}
Call `Children.map(children, fn, thisArg?)` to map or transform each child in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function RowList({ children }) {
return (
<div className="RowList">
{Children.map(children, child =>
<div className="Row">
{child}
</div>
)}
</div>
);
}
```
[See more examples below.](#transforming-children)
#### Parameters {/*children-map-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
* `fn`: The mapping function, similar to the [array `map` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call. You need to return a React node from this function. This may be an empty node (`null`, `undefined`, or a Boolean), a string, a number, a React element, or an array of other React nodes.
* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`.
#### Returns {/*children-map-returns*/}
If `children` is `null` or `undefined`, returns the same value.
Otherwise, returns a flat array consisting of the nodes you've returned from the `fn` function. The returned array will contain all nodes you returned except for `null` and `undefined`.
#### Caveats {/*children-map-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
- If you return an element or an array of elements with keys from `fn`, **the returned elements' keys will be automatically combined with the key of the corresponding original item from `children`.** When you return multiple elements from `fn` in an array, their keys only need to be unique locally amongst each other.
---
### `Children.only(children)` {/*children-only*/}
Call `Children.only(children)` to assert that `children` represent a single React element.
```js
function Box({ children }) {
const element = Children.only(children);
// ...
```
#### Parameters {/*children-only-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-only-returns*/}
If `children` [is a valid element,](/apis/react/isValidElement) returns that element.
Otherwise, throws an error.
#### Caveats {/*children-only-caveats*/}
- This method always **throws if you pass an array (such as the return value of `Children.map`) as `children`.** In other words, it enforces that `children` is a single React element, not that it's an array with a single element.
---
### `Children.toArray(children)` {/*children-toarray*/}
Call `Children.toArray(children)` to create an array out of the `children` data structure.
```js ReversedList.js active
import { Children } from 'react';
export default function ReversedList({ children }) {
const result = Children.toArray(children);
result.reverse();
// ...
```
#### Parameters {/*children-toarray-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-toarray-returns*/}
Returns a flat array of elements in `children`.
#### Caveats {/*children-toarray-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans) will be omitted in the returned array. **The returned elements' keys will be calculated from the original elements' keys and their level of nesting and position.** This ensures that flattening the array does not introduce changes in behavior.
---
## Usage {/*usage*/}
### Transforming children {/*transforming-children*/}
@ -766,171 +931,6 @@ This is another example of how parent and child components can cooperate without
---
## Reference {/*reference*/}
### `Children.count(children)` {/*children-count*/}
Call `Children.count(children)` to count the number of children in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function RowList({ children }) {
return (
<>
<h1>Total rows: {Children.count(children)}</h1>
...
</>
);
}
```
[See more examples above.](#counting-children)
#### Parameters {/*children-count-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-count-returns*/}
The number of nodes inside these `children`.
#### Caveats {/*children-count-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
---
### `Children.forEach(children, fn, thisArg?)` {/*children-foreach*/}
Call `Children.forEach(children, fn, thisArg?)` to run some code for each child in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function SeparatorList({ children }) {
const result = [];
Children.forEach(children, (child, index) => {
result.push(child);
result.push(<hr key={index} />);
});
// ...
```
[See more examples above.](#running-some-code-for-each-child)
#### Parameters {/*children-foreach-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
* `fn`: The function you want to run for each child, similar to the [array `forEach` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call.
* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`.
#### Returns {/*children-foreach-returns*/}
`Children.forEach` returns `undefined`.
#### Caveats {/*children-foreach-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
---
### `Children.map(children, fn, thisArg?)` {/*children-map*/}
Call `Children.map(children, fn, thisArg?)` to map or transform each child in the `children` data structure.
```js RowList.js active
import { Children } from 'react';
function RowList({ children }) {
return (
<div className="RowList">
{Children.map(children, child =>
<div className="Row">
{child}
</div>
)}
</div>
);
}
```
[See more examples above.](#transforming-children)
#### Parameters {/*children-map-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
* `fn`: The mapping function, similar to the [array `map` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call. You need to return a React node from this function. This may be an empty node (`null`, `undefined`, or a Boolean), a string, a number, a React element, or an array of other React nodes.
* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`.
#### Returns {/*children-map-returns*/}
If `children` is `null` or `undefined`, returns the same value.
Otherwise, returns a flat array consisting of the nodes you've returned from the `fn` function. The returned array will contain all nodes you returned except for `null` and `undefined`.
#### Caveats {/*children-map-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/apis/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/apis/react/Fragment) don't get traversed.
- If you return an element or an array of elements with keys from `fn`, **the returned elements' keys will be automatically combined with the key of the corresponding original item from `children`.** When you return multiple elements from `fn` in an array, their keys only need to be unique locally amongst each other.
---
### `Children.only(children)` {/*children-only*/}
Call `Children.only(children)` to assert that `children` represent a single React element.
```js
function Box({ children }) {
const element = Children.only(children);
// ...
```
#### Parameters {/*children-only-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-only-returns*/}
If `children` [is a valid element,](/apis/react/isValidElement) returns that element.
Otherwise, throws an error.
#### Caveats {/*children-only-caveats*/}
- This method always **throws if you pass an array (such as the return value of `Children.map`) as `children`.** In other words, it enforces that `children` is a single React element, not that it's an array with a single element.
---
### `Children.toArray(children)` {/*children-toarray*/}
Call `Children.toArray(children)` to create an array out of the `children` data structure.
```js ReversedList.js active
import { Children } from 'react';
export default function ReversedList({ children }) {
const result = Children.toArray(children);
result.reverse();
// ...
```
#### Parameters {/*children-toarray-parameters*/}
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns {/*children-toarray-returns*/}
Returns a flat array of elements in `children`.
#### Caveats {/*children-toarray-caveats*/}
- Empty nodes (`null`, `undefined`, and Booleans) will be omitted in the returned array. **The returned elements' keys will be calculated from the original elements' keys and their level of nesting and position.** This ensures that flattening the array does not introduce changes in behavior.
---
## Troubleshooting {/*troubleshooting*/}
### I pass a custom component, but the `Children` methods don't show its render result {/*i-pass-a-custom-component-but-the-children-methods-dont-show-its-render-result*/}

2610
beta/src/content/apis/react/Component.md

File diff suppressed because it is too large

38
beta/src/content/apis/react/Fragment.md

@ -19,6 +19,24 @@ title: <Fragment> (<>...</>)
---
## Reference {/*reference*/}
### `<Fragment>` {/*fragment*/}
Wrap elements in `<Fragment>` to group them together in situations where you need a single element. Grouping elements in `Fragment` has no effect on the resulting DOM; it is the same as if the elements were not grouped. The empty JSX tag `<></>` is shorthand for `<Fragment></Fragment>` in most cases.
#### Props {/*props*/}
- **optional** `key`: Fragments declared with the explicit `<Fragment>` syntax may have [keys.](https://beta.reactjs.org/learn/rendering-lists#keeping-list-items-in-order-with-key)
#### Caveats {/*caveats*/}
- If you want to pass `key` to a Fragment, you can't use the `<>...</>` syntax. You have to explicitly import `Fragment` from `'react'` and render `<Fragment key={yourKey}>...</Fragment>`.
- React does not [reset state](/learn/preserving-and-resetting-state) when you go from rendering `<><Child /></>` to `[<Child />]` or back, or when you go from rendering `<><Child /></>` to `<Child />` and back. This only works a single level deep: for example, going from `<><><Child /></></>` to `<Child />` resets the state. See the precise semantics [here.](https://gist.github.com/clemmy/b3ef00f9507909429d8aa0d3ee4f986b)
---
## Usage {/*usage*/}
### Returning multiple elements {/*returning-multiple-elements*/}
@ -190,23 +208,3 @@ function PostBody({ body }) {
```
</Sandpack>
---
## Reference {/*reference*/}
### `<Fragment>` {/*fragment*/}
Wrap elements in `<Fragment>` to group them together in situations where you need a single element. Grouping elements in `Fragment` has no effect on the resulting DOM; it is the same as if the elements were not grouped. The empty JSX tag `<></>` is shorthand for `<Fragment></Fragment>` in most cases.
#### Props {/*props*/}
- **optional** `key`: Fragments declared with the explicit `<Fragment>` syntax may have [keys.](https://beta.reactjs.org/learn/rendering-lists#keeping-list-items-in-order-with-key)
#### Caveats {/*caveats*/}
- If you want to pass `key` to a Fragment, you can't use the `<>...</>` syntax. You have to explicitly import `Fragment` from `'react'` and render `<Fragment key={yourKey}>...</Fragment>`.
- React does not [reset state](/learn/preserving-and-resetting-state) when you go from rendering `<><Child /></>` to `[<Child />]` or back, or when you go from rendering `<><Child /></>` to `<Child />` and back. This only works a single level deep: for example, going from `<><><Child /></></>` to `<Child />` resets the state. See the precise semantics [here.](https://gist.github.com/clemmy/b3ef00f9507909429d8aa0d3ee4f986b)

85
beta/src/content/apis/react/Profiler.md

@ -18,6 +18,50 @@ title: <Profiler>
---
## Reference {/*reference*/}
### `<Profiler>` {/*profiler*/}
Wrap a component tree in a `<Profiler>` to measure its rendering performance.
```js
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>
```
#### Props {/*props*/}
* `id`: A string identifying the part of the UI you are measuring.
* `onRender`: An [`onRender` callback](#onrender-callback) that React calls it every time components within the profiled tree update. It receives information about what was rendered and how much time it took.
#### Caveats {/*caveats*/}
* Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
---
### `onRender` callback {/*onrender-callback*/}
React will call your `onRender` callback with information about what was rendered.
```js
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// Aggregate or log render timings...
}
```
#### Parameters {/*onrender-parameters*/}
* `id`: The string `id` prop of the `<Profiler>` tree that has just committed. This lets you identify which part of the tree was committed if you are using multiple profilers.
* `phase`: Either `"mount"` or `"update"`. This lets you know whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or hooks.
* `actualDuration`: The number of milliseconds spent rendering the `<Profiler>` and its descendants for the current update. This indicates how well the subtree makes use of memoization (e.g. [`memo`](/apis/react/memo) and [`useMemo`](/apis/react/useMemo)). Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
* `baseDuration`: The number of milliseconds estimating how much time it would take to re-render the entire `<Profiler>` subtree without any optimizations. It is calculated by summing up the most recent render durations of each component in the tree. This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization). Compare `actualDuration` against it to see if memoization is working.
* `startTime`: A numeric timestamp for when React began rendering the current update.
* `endTime`: A numeric timestamp for when React committed the current update. This value is shared between all profilers in a commit, enabling them to be grouped if desirable.
---
## Usage {/*usage*/}
### Measuring rendering performance programmatically {/*measuring-rendering-performance-programmatically*/}
@ -86,44 +130,3 @@ Although `<Profiler>` is a lightweight component, it should be used only when ne
---
## Reference {/*reference*/}
### `<Profiler>` {/*profiler*/}
Wrap a component tree in a `<Profiler>` to measure its rendering performance.
```js
<Profiler id="App" onRender={onRender}>
<App />
</Profiler>
```
#### Props {/*props*/}
* `id`: A string identifying the part of the UI you are measuring.
* `onRender`: An [`onRender` callback](#onrender-callback) that React calls it every time components within the profiled tree update. It receives information about what was rendered and how much time it took.
#### Caveats {/*caveats*/}
* Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
---
### `onRender` callback {/*onrender-callback*/}
React will call your `onRender` callback with information about what was rendered.
```js
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// Aggregate or log render timings...
}
```
#### Parameters {/*onrender-parameters*/}
* `id`: The string `id` prop of the `<Profiler>` tree that has just committed. This lets you identify which part of the tree was committed if you are using multiple profilers.
* `phase`: Either `"mount"` or `"update"`. This lets you know whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or hooks.
* `actualDuration`: The number of milliseconds spent rendering the `<Profiler>` and its descendants for the current update. This indicates how well the subtree makes use of memoization (e.g. [`memo`](/apis/react/memo) and [`useMemo`](/apis/react/useMemo)). Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
* `baseDuration`: The number of milliseconds estimating how much time it would take to re-render the entire `<Profiler>` subtree without any optimizations. It is calculated by summing up the most recent render durations of each component in the tree. This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization). Compare `actualDuration` against it to see if memoization is working.
* `startTime`: A numeric timestamp for when React began rendering the current update.
* `endTime`: A numeric timestamp for when React committed the current update. This value is shared between all profilers in a commit, enabling them to be grouped if desirable.

48
beta/src/content/apis/react/PureComponent.md

@ -26,6 +26,29 @@ class Greeting extends PureComponent {
---
## Reference {/*reference*/}
### `PureComponent` {/*purecomponent*/}
To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/apis/react/Component)
```js
import { PureComponent } from 'react';
class Greeting extends PureComponent {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
```
`PureComponent` is a subclass of `Component` and supports [all the `Component` APIs.](/apis/react/Component#reference) Extending `PureComponent` is equivalent to defining a custom [`shouldComponentUpdate`](/apis/react/Component#shouldcomponentupdate) method that shallowly compares props and state.
[See more examples below.](#usage)
---
## Usage {/*usage*/}
### Skipping unnecessary re-renders for class components {/*skipping-unnecessary-re-renders-for-class-components*/}
@ -183,28 +206,3 @@ label {
Unlike `PureComponent`, [`memo`](/apis/react/memo) does not compare the new and the old state. In function components, calling the [`set` function](/apis/react/useState#setstate) with the same state [already prevents re-renders by default,](/apis/react/memo#updating-a-memoized-component-using-state) even without `memo`.
</Note>
---
## Reference {/*reference*/}
### `PureComponent` {/*purecomponent*/}
To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/apis/react/Component)
```js
import { PureComponent } from 'react';
class Greeting extends PureComponent {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
```
`PureComponent` is a subclass of `Component` and supports [all the `Component` APIs.](/apis/react/Component#reference) Extending `PureComponent` is equivalent to defining a custom [`shouldComponentUpdate`](/apis/react/Component#shouldcomponentupdate) method that shallowly compares props and state.
[See more examples.](#usage)

72
beta/src/content/apis/react/StrictMode.md

@ -20,6 +20,42 @@ title: <StrictMode>
---
## Reference {/*reference*/}
### `<StrictMode>` {/*strictmode*/}
Use `StrictMode` to enable additional development behaviors and warnings for the entire component tree inside:
```js
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
[See more examples below.](#usage)
Strict Mode enables the following development-only behaviors:
- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering.
- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup.
- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode)
#### Props {/*props*/}
`StrictMode` accepts no props.
#### Caveats {/*caveats*/}
* There is no way to opt out of Strict Mode inside a tree wrapped in `<StrictMode>`. This gives you confidence that all components inside `<StrictMode>` are checked. If two teams working on a product disagree whether they find the checks valuable, they need to either reach consensus or move `<StrictMode>` down in the tree.
---
## Usage {/*usage*/}
### Enabling Strict Mode for entire app {/*enabling-strict-mode-for-entire-app*/}
@ -792,39 +828,3 @@ React warns if some component anywhere inside a `<StrictMode>` tree uses one of
* Legacy string refs ([`this.refs`](/apis/react/Component#refs)). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage)
These APIs are primarily used in older [class components](/apis/react/Component) so they rarely appear in modern apps.
---
## Reference {/*reference*/}
### `<StrictMode>` {/*strictmode*/}
Use `StrictMode` to enable additional development behaviors and warnings for the entire component tree inside:
```js
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(
<StrictMode>
<App />
</StrictMode>
);
```
[See examples above.](#usage)
Strict Mode enables the following development-only behaviors:
- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering.
- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup.
- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode)
#### Props {/*props*/}
`StrictMode` accepts no props.
#### Caveats {/*caveats*/}
* There is no way to opt out of Strict Mode inside a tree wrapped in `<StrictMode>`. This gives you confidence that all components inside `<StrictMode>` are checked. If two teams working on a product disagree whether they find the checks valuable, they need to either reach consensus or move `<StrictMode>` down in the tree.

34
beta/src/content/apis/react/Suspense.md

@ -19,6 +19,23 @@ title: <Suspense>
---
## Reference {/*reference*/}
### `<Suspense>` {/*suspense*/}
#### Props {/*props*/}
* `children`: The actual UI you intend to render. If `children` suspends while rendering, the Suspense boundary will switch to rendering `fallback`.
* `fallback`: An alternate UI to render in place of the actual UI if it has not finished loading. Any valid React node is accepted, though in practice, a fallback is a lightweight placeholder view, such as a loading spinner or skeleton. Suspense will automatically switch to `fallback` when `children` suspends, and back to `children` when the data is ready. If `fallback` suspends while rendering, it will activate the closest parent Suspense boundary.
#### Caveats {/*caveats*/}
- React does not preserve any state for renders that got suspended before they were able to mount for the first time. When the component has loaded, React will retry rendering the suspended tree from scratch.
- If Suspense was displaying content for the tree, but then it suspended again, the `fallback` will be shown again unless the update causing it was caused by [`startTransition`](/apis/react/startTransition) or [`useDeferredValue`](/apis/react/useDeferredValue).
- If React needs to hide the already visible content because it suspended again, it will clean up [layout Effects](/apis/react/useLayoutEffect) in the content tree. When the content is ready to be shown again, React will fire the layout Effects again. This lets you make sure that Effects measuring the DOM layout don't try to do this while the content is hidden.
- React includes under-the-hood optimizations like *Streaming Server Rendering* and *Selective Hydration* that are integrated with Suspense. Read [an architectural overview](https://github.com/reactwg/react-18/discussions/37) and watch [a technical talk](https://www.youtube.com/watch?v=pj5N-Khihgc) to learn more.
---
## Usage {/*usage*/}
### Displaying a fallback while content is loading {/*displaying-a-fallback-while-content-is-loading*/}
@ -2521,23 +2538,6 @@ The server HTML will include the loading indicator. It will be replaced by the `
---
## Reference {/*reference*/}
### `<Suspense>` {/*suspense*/}
#### Props {/*props*/}
* `children`: The actual UI you intend to render. If `children` suspends while rendering, the Suspense boundary will switch to rendering `fallback`.
* `fallback`: An alternate UI to render in place of the actual UI if it has not finished loading. Any valid React node is accepted, though in practice, a fallback is a lightweight placeholder view, such as a loading spinner or skeleton. Suspense will automatically switch to `fallback` when `children` suspends, and back to `children` when the data is ready. If `fallback` suspends while rendering, it will activate the closest parent Suspense boundary.
#### Caveats {/*caveats*/}
- React does not preserve any state for renders that got suspended before they were able to mount for the first time. When the component has loaded, React will retry rendering the suspended tree from scratch.
- If Suspense was displaying content for the tree, but then it suspended again, the `fallback` will be shown again unless the update causing it was caused by [`startTransition`](/apis/react/startTransition) or [`useDeferredValue`](/apis/react/useDeferredValue).
- If React needs to hide the already visible content because it suspended again, it will clean up [layout Effects](/apis/react/useLayoutEffect) in the content tree. When the content is ready to be shown again, React will fire the layout Effects again. This lets you make sure that Effects measuring the DOM layout don't try to do this while the content is hidden.
- React includes under-the-hood optimizations like *Streaming Server Rendering* and *Selective Hydration* that are integrated with Suspense. Read [an architectural overview](https://github.com/reactwg/react-18/discussions/37) and watch [a technical talk](https://www.youtube.com/watch?v=pj5N-Khihgc) to learn more.
---
## Troubleshooting {/*troubleshooting*/}
### How do I prevent the UI from being replaced by a fallback during an update? {/*preventing-unwanted-fallbacks*/}

104
beta/src/content/apis/react/cloneElement.md

@ -22,6 +22,58 @@ const clonedElement = cloneElement(element, props, ...children)
---
## Reference {/*reference*/}
### `cloneElement(element, props, ...children)` {/*cloneelement*/}
Call `cloneElement` to create a React element based on the `element`, but with different `props` and `children`:
```js
import { cloneElement } from 'react';
// ...
const clonedElement = cloneElement(
<Row title="Cabbage">
Hello
</Row>,
{ isHighlighted: true },
'Goodbye'
);
console.log(clonedElement); // <Row title="Cabbage">Goodbye</Row>
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `element`: The `element` argument must be a valid React element. For example, it could be a JSX node like `<Something />`, the result of calling [`createElement`](/apis/react/createElement), or the result of another `cloneElement` call.
* `props`: The `props` argument must either be an object or `null`. If you pass `null`, the cloned element will retain all of the original `element.props`. Otherwise, for every prop in the `props` object, the returned element will "prefer" the value from `props` over the value from `element.props`. The rest of the props will be filled from the original `element.props`. If you pass `props.key` or `props.ref`, they will replace the original ones.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. If you don't pass any `...children` arguments, the original `element.props.children` will be preserved.
#### Returns {/*returns*/}
`cloneElement` returns a React element object with a few properties:
* `type`: Same as `element.type`.
* `props`: The result of shallowly merging `element.props` with the overriding `props` you have passed.
* `ref`: The original `element.ref`, unless it was overridden by `props.ref`.
* `key`: The original `element.key`, unless it was overridden by `props.key`.
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
#### Caveats {/*caveats*/}
* Cloning an element **does not modify the original element.**
* You should only **pass children as multiple arguments to `cloneElement` if they are all statically known,** like `cloneElement(element, null, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `cloneElement(element, null, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
* `cloneElement` makes it harder to trace the data flow, so **try the [alternatives](/#alternatives) instead.**
---
## Usage {/*usage*/}
### Overriding props of an element {/*overriding-props-of-an-element*/}
@ -640,55 +692,3 @@ button {
</Sandpack>
This approach is particularly useful if you want to reuse this logic between different components.
---
## Reference {/*reference*/}
### `cloneElement(element, props, ...children)` {/*cloneelement*/}
Call `cloneElement` to create a React element based on the `element`, but with different `props` and `children`:
```js
import { cloneElement } from 'react';
// ...
const clonedElement = cloneElement(
<Row title="Cabbage">
Hello
</Row>,
{ isHighlighted: true },
'Goodbye'
);
console.log(clonedElement); // <Row title="Cabbage">Goodbye</Row>
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `element`: The `element` argument must be a valid React element. For example, it could be a JSX node like `<Something />`, the result of calling [`createElement`](/apis/react/createElement), or the result of another `cloneElement` call.
* `props`: The `props` argument must either be an object or `null`. If you pass `null`, the cloned element will retain all of the original `element.props`. Otherwise, for every prop in the `props` object, the returned element will "prefer" the value from `props` over the value from `element.props`. The rest of the props will be filled from the original `element.props`. If you pass `props.key` or `props.ref`, they will replace the original ones.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. If you don't pass any `...children` arguments, the original `element.props.children` will be preserved.
#### Returns {/*returns*/}
`cloneElement` returns a React element object with a few properties:
* `type`: Same as `element.type`.
* `props`: The result of shallowly merging `element.props` with the overriding `props` you have passed.
* `ref`: The original `element.ref`, unless it was overridden by `props.ref`.
* `key`: The original `element.key`, unless it was overridden by `props.key`.
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
#### Caveats {/*caveats*/}
* Cloning an element **does not modify the original element.**
* You should only **pass children as multiple arguments to `cloneElement` if they are all statically known,** like `cloneElement(element, null, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `cloneElement(element, null, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
* `cloneElement` makes it harder to trace the data flow, so **try the [alternatives](/#alternatives) instead.**

164
beta/src/content/apis/react/createContext.md

@ -16,6 +16,88 @@ const SomeContext = createContext(defaultValue)
---
## Reference {/*reference*/}
### `createContext(defaultValue)` {/*createcontext*/}
Call `createContext` outside of any components to create a context.
```js
import { createContext } from 'react';
const ThemeContext = createContext('light');
```
#### Parameters {/*parameters*/}
* `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time.
#### Returns {/*returns*/}
`createContext` returns a context object.
**The context object itself does not hold any information.** It represents _which_ context other components can read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/apis/react/useContext) in components below to read it. The context object has a few properties:
* `SomeContext.Provider` lets you provide the context value to components.
* `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
---
### `SomeContext.Provider` {/*provider*/}
Wrap your components into a context provider to specify the value of this context for all components inside:
```js
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
```
#### Props {/*provider-props*/}
* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/apis/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
---
### `SomeContext.Consumer` {/*consumer*/}
Before `useContext` existed, there was an older way to read context:
```js
function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}
```
Although this older way still works, but **newly written code should read context with [`useContext()`](/apis/react/useContext) instead:**
```js
function Button() {
// ✅ Recommended way
const theme = useContext(ThemeContext);
return <button className={theme} />;
}
```
#### Props {/*consumer-props*/}
* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/apis/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context passed from the parent components have changed.
---
## Usage {/*usage*/}
### Creating context {/*creating-context*/}
@ -116,88 +198,6 @@ This works similar to [importing and exporting components.](/learn/importing-and
---
## Reference {/*reference*/}
### `createContext(defaultValue)` {/*createcontext*/}
Call `createContext` outside of any components to create a context.
```js
import { createContext } from 'react';
const ThemeContext = createContext('light');
```
#### Parameters {/*parameters*/}
* `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time.
#### Returns {/*returns*/}
`createContext` returns a context object.
**The context object itself does not hold any information.** It represents _which_ context other components can read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/apis/react/useContext) in components below to read it. The context object has a few properties:
* `SomeContext.Provider` lets you provide the context value to components.
* `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
---
### `SomeContext.Provider` {/*provider*/}
Wrap your components into a context provider to specify the value of this context for all components inside:
```js
function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}
```
#### Props {/*provider-props*/}
* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/apis/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
---
### `SomeContext.Consumer` {/*consumer*/}
Before `useContext` existed, there was an older way to read context:
```js
function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}
```
Although this older way still works, but **newly written code should read context with [`useContext()`](/apis/react/useContext) instead:**
```js
function Button() {
// ✅ Recommended way
const theme = useContext(ThemeContext);
return <button className={theme} />;
}
```
#### Props {/*consumer-props*/}
* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/apis/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context passed from the parent components have changed.
---
## Troubleshooting {/*troubleshooting*/}
### I can't find a way to change the context value {/*i-cant-find-a-way-to-change-the-context-value*/}

98
beta/src/content/apis/react/createElement.md

@ -16,6 +16,55 @@ const element = createElement(type, props, ...children)
---
## Reference {/*reference*/}
### `createElement(type, props, ...children)` {/*createelement*/}
Call `createElement` to create a React element with the given `type`, `props`, and `children`.
```js
import { createElement } from 'react';
function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello'
);
}
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/apis/react/Fragment)).
* `props`: The `props` argument must either be an object or `null`. If you pass `null`, it will be treated the same as an empty object. React will create an element with props matching the `props` you have passed. Note that `ref` and `key` from your `props` object are special and will *not* be available as `element.props.ref` and `element.props.key` on the returned `element`. They will be available as `element.ref` and `element.key`.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
#### Returns {/*returns*/}
`createElement` returns a React element object with a few properties:
* `type`: The `type` you have passed.
* `props`: The `props` you have passed except for `ref` and `key`. If the `type` is a component with legacy `type.defaultProps`, then any missing or undefined `props` will get the values from `type.defaultProps`.
* `ref`: The `ref` you have passed. If missing, `null`.
* `key`: The `key` you have passed, coerced to a string. If missing, `null`.
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
#### Caveats {/*caveats*/}
* You must **treat React elements and their props as [immutable](https://en.wikipedia.org/wiki/Immutable_object)** and never change their contents after creation. In development, React will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) the returned element and its `props` property shallowly to enforce this.
* When you use JSX, **you must start a tag with a capital letter to render your own custom component.** In other words, `<Something />` is equivalent to `createElement(Something)`, but `<something />` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag).
* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `createElement('h1', {}, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `createElement('ul', {}, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
---
## Usage {/*usage*/}
### Creating an element without JSX {/*creating-an-element-without-jsx*/}
@ -154,52 +203,3 @@ A React element is more like a description--an instruction for React to later re
Creating elements is extremely cheap so you don't need to try to optimize or avoid it.
</DeepDive>
---
## Reference {/*reference*/}
### `createElement(type, props, ...children)` {/*createelement*/}
Call `createElement` to create a React element with the given `type`, `props`, and `children`.
```js
import { createElement } from 'react';
function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello'
);
}
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/apis/react/Fragment)).
* `props`: The `props` argument must either be an object or `null`. If you pass `null`, it will be treated the same as an empty object. React will create an element with props matching the `props` you have passed. Note that `ref` and `key` from your `props` object are special and will *not* be available as `element.props.ref` and `element.props.key` on the returned `element`. They will be available as `element.ref` and `element.key`.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
#### Returns {/*returns*/}
`createElement` returns a React element object with a few properties:
* `type`: The `type` you have passed.
* `props`: The `props` you have passed except for `ref` and `key`. If the `type` is a component with legacy `type.defaultProps`, then any missing or undefined `props` will get the values from `type.defaultProps`.
* `ref`: The `ref` you have passed. If missing, `null`.
* `key`: The `key` you have passed, coerced to a string. If missing, `null`.
Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
#### Caveats {/*caveats*/}
* You must **treat React elements and their props as [immutable](https://en.wikipedia.org/wiki/Immutable_object)** and never change their contents after creation. In development, React will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) the returned element and its `props` property shallowly to enforce this.
* When you use JSX, **you must start a tag with a capital letter to render your own custom component.** In other words, `<Something />` is equivalent to `createElement(Something)`, but `<something />` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag).
* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `createElement('h1', {}, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `createElement('ul', {}, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.

80
beta/src/content/apis/react/createFactory.md

@ -22,6 +22,46 @@ const factory = createFactory(type)
---
## Reference {/*reference*/}
### `createFactory(type)` {/*createfactory*/}
<Deprecated>
This API will be removed in a future major version of React. [See the alternatives.](#alternatives)
</Deprecated>
Call `createFactory(type)` to create a factory function which produces React elements of a given `type`.
```js
import { createFactory } from 'react';
const button = createFactory('button');
```
Then you can use it to create React elements without JSX:
```js
export default function App() {
return button({
onClick: () => {
alert('Clicked!')
}
}, 'Click me');
}
```
#### Parameters {/*parameters*/}
* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/apis/react/Fragment)).
#### Returns {/*returns*/}
Returns a factory function. That factory function receives a `props` object as the first argument, followed by a list of `...children` arguments, and returns a React element with the given `type`, `props` and `children`.
---
## Usage {/*usage*/}
### Creating React elements with a factory {/*creating-react-elements-with-a-factory*/}
@ -199,43 +239,3 @@ function Heading({ isSubheading, ...props }) {
Otherwise React will interpret `<type>` as a built-in HTML tag because it is lowercase.
</Pitfall>
---
## Reference {/*reference*/}
### `createFactory(type)` {/*createfactory*/}
<Deprecated>
This API will be removed in a future major version of React. [See the alternatives.](#alternatives)
</Deprecated>
Call `createFactory(type)` to create a factory function which produces React elements of a given `type`.
```js
import { createFactory } from 'react';
const button = createFactory('button');
```
Then you can use it to create React elements without JSX:
```js
export default function App() {
return button({
onClick: () => {
alert('Clicked!')
}
}, 'Click me');
}
```
#### Parameters {/*parameters*/}
* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/apis/react/Fragment)).
#### Returns {/*returns*/}
Returns a factory function. That factory function receives a `props` object as the first argument, followed by a list of `...children` arguments, and returns a React element with the given `type`, `props` and `children`.

80
beta/src/content/apis/react/createRef.md

@ -25,6 +25,45 @@ class MyInput extends Component {
---
## Reference {/*reference*/}
### `createRef()` {/*createref*/}
Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [class component.](/apis/react/Component)
```js
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...
```
<Pitfall>
`createRef` is mostly used for [class components.](/apis/react/Component) Function components typically rely on [`useRef`](/apis/react/useRef) instead.
</Pitfall>
#### Parameters {/*parameters*/}
`createRef` takes no parameters.
#### Returns {/*returns*/}
`createRef` returns an object with a single property:
* `current`: Initially, it's set to the `null`. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property.
#### Caveats {/*caveats*/}
* `createRef` always returns a *different* object. It's equivalent to writing `{ current: null }` yourself.
* In a function component, you probably want [`useRef`](/apis/react/useRef) instead which always returns the same object.
* `const ref = useRef()` is equivalent to `const [ref, _] = useState(() => createRef(null))`.
---
## Usage {/*usage*/}
### Declaring a ref in a class component {/*declaring-a-ref-in-a-class-component*/}
@ -137,44 +176,3 @@ export default function Form() {
```
</Sandpack>
---
## Reference {/*reference*/}
### `createRef()` {/*createref*/}
Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [class component.](/apis/react/Component)
```js
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...
```
<Pitfall>
`createRef` is mostly used for [class components.](/apis/react/Component) Function components typically rely on [`useRef`](/apis/react/useRef) instead.
</Pitfall>
#### Parameters {/*parameters*/}
`createRef` takes no parameters.
#### Returns {/*returns*/}
`createRef` returns an object with a single property:
* `current`: Initially, it's set to the `null`. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property.
#### Caveats {/*caveats*/}
* `createRef` always returns a *different* object. It's equivalent to writing `{ current: null }` yourself.
* In a function component, you probably want [`useRef`](/apis/react/useRef) instead which always returns the same object.
* `const ref = useRef()` is equivalent to `const [ref, _] = useState(() => createRef(null))`.

114
beta/src/content/apis/react/forwardRef.md

@ -16,6 +16,63 @@ const SomeComponent = forwardRef(render)
---
## Reference {/*reference*/}
### `forwardRef(render)` {/*forwardref*/}
Call `forwardRef()` to let your component receive a ref and forward it to a child component:
```js
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
// ...
});
```
#### Parameters {/*parameters*/}
* `render`: The render function for your component. React calls this function with the props and `ref` that your component received from its parent. The JSX you return will be the output of your component.
#### Returns {/*returns*/}
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by `forwardRef` is also able to receive a `ref` prop.
#### Caveats {/*caveats*/}
* In Strict Mode, React will **call your render function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
### `render` function {/*render-function*/}
`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`:
```js
const MyInput = forwardRef(function MyInput(props, ref) {
return (
<label>
{props.label}
<input ref={ref} />
</label>
);
});
```
#### Parameters {/*render-parameters*/}
* `props`: The props passed by the parent component.
* `ref`: The `ref` attribute passed by the parent component. The `ref` can be an object or a function. If the parent component has not passed a ref, it will be `null`. You should either pass the `ref` you receive to another component, or pass it to [`useImperativeHandle`.](/apis/react/useImperativeHandle)
#### Returns {/*render-returns*/}
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by `forwardRef` is able to take a `ref` prop.
---
## Usage {/*usage*/}
### Exposing a DOM node to the parent component {/*exposing-a-dom-node-to-the-parent-component*/}
@ -417,63 +474,6 @@ input {
---
## Reference {/*reference*/}
### `forwardRef(render)` {/*forwardref*/}
Call `forwardRef()` to let your component receive a ref and forward it to a child component:
```js
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
// ...
});
```
#### Parameters {/*parameters*/}
* `render`: The render function for your component. React calls this function with the props and `ref` that your component received from its parent. The JSX you return will be the output of your component.
#### Returns {/*returns*/}
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by `forwardRef` is also able to receive a `ref` prop.
#### Caveats {/*caveats*/}
* In Strict Mode, React will **call your render function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
### `render` function {/*render-function*/}
`forwardRef` accepts a render function as an argument. React calls this function with `props` and `ref`:
```js
const MyInput = forwardRef(function MyInput(props, ref) {
return (
<label>
{props.label}
<input ref={ref} />
</label>
);
});
```
#### Parameters {/*render-parameters*/}
* `props`: The props passed by the parent component.
* `ref`: The `ref` attribute passed by the parent component. The `ref` can be an object or a function. If the parent component has not passed a ref, it will be `null`. You should either pass the `ref` you receive to another component, or pass it to [`useImperativeHandle`.](/apis/react/useImperativeHandle)
#### Returns {/*render-returns*/}
`forwardRef` returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by `forwardRef` is able to take a `ref` prop.
---
## Troubleshooting {/*troubleshooting*/}
### My component is wrapped in `forwardRef`, but the `ref` to it is always `null` {/*my-component-is-wrapped-in-forwardref-but-the-ref-to-it-is-always-null*/}

70
beta/src/content/apis/react/isValidElement.md

@ -16,6 +16,41 @@ const isElement = isValidElement(value)
---
## Reference {/*reference*/}
### `isValidElement(value)` {/*isvalidelement*/}
Call `isValidElement(value)` to check whether `value` is a React element.
```js
import { isValidElement } from 'react';
// ✅ React elements
console.log(isValidElement(<p />)); // true
console.log(isValidElement(createElement('p'))); // true
// ❌ Not React elements
console.log(isValidElement(25)); // false
console.log(isValidElement('Hello')); // false
console.log(isValidElement({ age: 42 })); // false
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `value`: The `value` you want to check. It can be any a value of any type.
#### Returns {/*returns*/}
`isValidElement` returns `true` if the `value` is a React element. Otherwise, it returns `false`.
#### Caveats {/*caveats*/}
* **Only [JSX tags](/learn/writing-markup-with-jsx) and objects returned by [`createElement`](/apis/react/createElement) are considered to be React elements.** For example, even though a number like `42` is a valid React *node* (and can be returned from a component), it is not a valid React element. Arrays and portals created with [`createPortal`](/apis/react-dom/createPortal) are also *not* considered to be React elements.
---
## Usage {/*usage*/}
### Checking if something is a React element {/*checking-if-something-is-a-react-element*/}
@ -91,38 +126,3 @@ function MyComponent() {
This is why you shouldn't use `isValidElement` as a way to check whether something can be rendered.
</DeepDive>
---
## Reference {/*reference*/}
### `isValidElement(value)` {/*isvalidelement*/}
Call `isValidElement(value)` to check whether `value` is a React element.
```js
import { isValidElement } from 'react';
// ✅ React elements
console.log(isValidElement(<p />)); // true
console.log(isValidElement(createElement('p'))); // true
// ❌ Not React elements
console.log(isValidElement(25)); // false
console.log(isValidElement('Hello')); // false
console.log(isValidElement({ age: 42 })); // false
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `value`: The `value` you want to check. It can be any a value of any type.
#### Returns {/*returns*/}
`isValidElement` returns `true` if the `value` is a React element. Otherwise, it returns `false`.
#### Caveats {/*caveats*/}
* **Only [JSX tags](/learn/writing-markup-with-jsx) and objects returned by [`createElement`](/apis/react/createElement) are considered to be React elements.** For example, even though a number like `42` is a valid React *node* (and can be returned from a component), it is not a valid React element. Arrays and portals created with [`createPortal`](/apis/react-dom/createPortal) are also *not* considered to be React elements.

64
beta/src/content/apis/react/lazy.md

@ -16,6 +16,38 @@ const SomeComponent = lazy(load)
---
## Reference {/*reference*/}
### `lazy(load)` {/*lazy*/}
Call `lazy` outside your components to declare a lazy-loaded React component:
```js
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
#### Parameters {/*parameters*/}
* `load`: A function that returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or some other *thenable* (a Promise-like object with a `then` method). React will not call `load` until the first time you attempt to render the returned component. After React first calls `load`, it will wait for it to resolve, and then render the resolved value as a React component. Both the returned Promise and the Promise's resolved value will be cached, so React will not call `load` more than once. If the Promise rejects, React will `throw` the rejection reason to let the closest Error Boundary above handle it.
#### Returns {/*returns*/}
`lazy` returns a React component that you can render in your tree. While the code for the lazy component is still loading, attempting to render it will *suspend.* Use [`<Suspense>`](/apis/react/Suspense) to display a loading indicator while it's loading.
---
### `load` function {/*load*/}
#### Parameters {/*load-parameters*/}
`load` receives no parameters.
#### Returns {/*load-returns*/}
You need to return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or some other *thenable* (a Promise-like object with a `then` method). It needs to eventually resolve to a valid React component type, such as a function, [`memo`](/apis/react/memo), or a [`forwardRef`](/apis/react/forwardRef) component.
---
## Usage {/*usage*/}
### Lazy-loading components with Suspense {/*suspense-for-code-splitting*/}
@ -145,38 +177,6 @@ This demo loads with an artificial delay. The next time you untick and tick the
---
## Reference {/*reference*/}
### `lazy(load)` {/*lazy*/}
Call `lazy` outside your components to declare a lazy-loaded React component:
```js
const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
```
#### Parameters {/*parameters*/}
* `load`: A function that returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or some other *thenable* (a Promise-like object with a `then` method). React will not call `load` until the first time you attempt to render the returned component. After React first calls `load`, it will wait for it to resolve, and then render the resolved value as a React component. Both the returned Promise and the Promise's resolved value will be cached, so React will not call `load` more than once. If the Promise rejects, React will `throw` the rejection reason to let the closest Error Boundary above handle it.
#### Returns {/*returns*/}
`lazy` returns a React component that you can render in your tree. While the code for the lazy component is still loading, attempting to render it will *suspend.* Use [`<Suspense>`](/apis/react/Suspense) to display a loading indicator while it's loading.
---
### `load` function {/*load*/}
#### Parameters {/*load-parameters*/}
`load` receives no parameters.
#### Returns {/*load-returns*/}
You need to return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or some other *thenable* (a Promise-like object with a `then` method). It needs to eventually resolve to a valid React component type, such as a function, [`memo`](/apis/react/memo), or a [`forwardRef`](/apis/react/forwardRef) component.
---
## Troubleshooting {/*troubleshooting*/}
### My `lazy` component's state gets reset unexpectedly {/*my-lazy-components-state-gets-reset-unexpectedly*/}

56
beta/src/content/apis/react/memo.md

@ -16,6 +16,34 @@ const MemoizedComponent = memo(SomeComponent, arePropsEqual?)
---
## Reference {/*reference*/}
### `memo(Component, arePropsEqual?)` {/*memo*/}
Call `memo` outside of any components to define a memoized version of a component. This memoized component will usually not be re-rendered when its parent component is re-rendered as long as its props have not changed. But React may still re-render it: memoization is only a performance optimization, not a guarantee.
```js
import { memo } from 'react';
function SomeComponent(props) {
// ...
}
const MemoizedComponent = memo(SomeComponent);
```
#### Parameters {/*parameters*/}
* `Component`: The component that you want to memoize. The `memo` does not modify this component, but returns a new, memoized component instead. Any valid React component, including functions and [`forwardRef`](/apis/react/forwardRef) components, is accepted.
* **optional** `arePropsEqual`: A function that accepts two arguments: the component's previous props, and its new props. It should return `true` if the old and new props are equal: that is, if the component will render the same output and behave in the same way with the new props as with the old. Otherwise it should return `false`.
#### Returns {/*returns*/}
`memo` returns a new React component. It behaves the same as the component provided to `memo` except that React will not always re-render it when its parent is being re-rendered unless its props have changed.
---
## Usage {/*usage*/}
### Skipping re-rendering when props are unchanged {/*skipping-re-rendering-when-props-are-unchanged*/}
@ -329,34 +357,6 @@ Avoid doing deep equality checks inside `arePropsEqual` unless you are 100% sure
---
## Reference {/*reference*/}
### `memo(Component, arePropsEqual?)` {/*memo*/}
Call `memo` outside of any components to define a memoized version of a component. This memoized component will usually not be re-rendered when its parent component is re-rendered as long as its props have not changed. But React may still re-render it: memoization is only a performance optimization, not a guarantee.
```js
import { memo } from 'react';
function SomeComponent(props) {
// ...
}
const MemoizedComponent = memo(SomeComponent);
```
#### Parameters {/*parameters*/}
* `Component`: The component that you want to memoize. The `memo` does not modify this component, but returns a new, memoized component instead. Any valid React component, including functions and [`forwardRef`](/apis/react/forwardRef) components, is accepted.
* **optional** `arePropsEqual`: A function that accepts two arguments: the component's previous props, and its new props. It should return `true` if the old and new props are equal: that is, if the component will render the same output and behave in the same way with the new props as with the old. Otherwise it should return `false`.
#### Returns {/*returns*/}
`memo` returns a new React component. It behaves the same as the component provided to `memo` except that React will not always re-render it when its parent is being re-rendered unless its props have changed.
---
## Troubleshooting {/*troubleshooting*/}
### My component re-renders when a prop is an object, array, or function {/*my-component-rerenders-when-a-prop-is-an-object-or-array*/}

57
beta/src/content/apis/react/startTransition.md

@ -16,11 +16,11 @@ startTransition(scope)
---
## Usage {/*usage*/}
## Reference {/*reference*/}
### Marking a state update as a non-blocking transition {/*marking-a-state-update-as-a-non-blocking-transition*/}
### `startTransition(scope)` {/*starttransitionscope*/}
You can mark a state update as a *transition* by wrapping it in a `startTransition` call:
The `startTransition` function lets you mark a state update as a transition.
```js {7,9}
import { startTransition } from 'react';
@ -37,25 +37,35 @@ function TabContainer() {
}
```
Transitions let you keep the user interface updates responsive even on slow devices.
#### Parameters {/*parameters*/}
With a transition, your UI stays responsive in the middle of a re-render. For example, if the user clicks a tab but then change their mind and click another tab, they can do that without waiting for the first re-render to finish.
* `scope`: A function that updates some state by calling one or more [`set` functions.](/apis/react/useState#setstate) React immediately calls `scope` with no parameters and marks all state updates scheduled synchronously during the `scope` function call as transitions. They will be [non-blocking](/apis/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](/apis/react/useTransition#preventing-unwanted-loading-indicators)
<Note>
#### Returns {/*returns*/}
`startTransition` is very similar to [`useTransition`](/apis/react/useTransition), except that it does not provide the `isPending` flag to track whether a transition is ongoing. You can call `startTransition` when `useTransition` is not available. For example, `startTransition` works outside components, such as from a data library.
`startTransition` does not return anything.
[Learn about transitions and see examples on the `useTransition` page.](/apis/react/useTransition)
#### Caveats {/*caveats*/}
</Note>
* `startTransition` does not provide a way to track whether a transition is pending. To show a pending indicator while the transition is ongoing, you need [`useTransition`](/apis/react/useTransition) instead.
* You can wrap an update into a transition only if you have access to the `set` function of that state. If you want to start a transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](/apis/react/usedeferredvalue) instead.
* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as transitions.
* A state update marked as a transition will be interrupted by other state updates. For example, if you update a chart component inside a transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update.
* Transition updates can't be used to control text inputs.
* If there are multiple ongoing transitions, React currently batches them together. This is a limitation that will likely be removed in a future release.
---
## Reference {/*reference*/}
## Usage {/*usage*/}
### `startTransition(scope)` {/*starttransitionscope*/}
### Marking a state update as a non-blocking transition {/*marking-a-state-update-as-a-non-blocking-transition*/}
The `startTransition` function lets you mark a state update as a transition.
You can mark a state update as a *transition* by wrapping it in a `startTransition` call:
```js {7,9}
import { startTransition } from 'react';
@ -72,25 +82,14 @@ function TabContainer() {
}
```
Transitions let you keep the user interface updates responsive even on slow devices.
#### Parameters {/*parameters*/}
* `scope`: A function that updates some state by calling one or more [`set` functions.](/apis/react/useState#setstate) React immediately calls `scope` with no parameters and marks all state updates scheduled synchronously during the `scope` function call as transitions. They will be [non-blocking](/apis/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](/apis/react/useTransition#preventing-unwanted-loading-indicators)
#### Returns {/*returns*/}
`startTransition` does not return anything.
#### Caveats {/*caveats*/}
* `startTransition` does not provide a way to track whether a transition is pending. To show a pending indicator while the transition is ongoing, you need [`useTransition`](/apis/react/useTransition) instead.
* You can wrap an update into a transition only if you have access to the `set` function of that state. If you want to start a transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](/apis/react/usedeferredvalue) instead.
With a transition, your UI stays responsive in the middle of a re-render. For example, if the user clicks a tab but then change their mind and click another tab, they can do that without waiting for the first re-render to finish.
* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as transitions.
<Note>
* A state update marked as a transition will be interrupted by other state updates. For example, if you update a chart component inside a transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update.
`startTransition` is very similar to [`useTransition`](/apis/react/useTransition), except that it does not provide the `isPending` flag to track whether a transition is ongoing. You can call `startTransition` when `useTransition` is not available. For example, `startTransition` works outside components, such as from a data library.
* Transition updates can't be used to control text inputs.
[Learn about transitions and see examples on the `useTransition` page.](/apis/react/useTransition)
* If there are multiple ongoing transitions, React currently batches them together. This is a limitation that will likely be removed in a future release.
</Note>

78
beta/src/content/apis/react/useCallback.md

@ -16,6 +16,45 @@ const cachedFn = useCallback(fn, dependencies)
---
## Reference {/*reference*/}
### `useCallback(fn, dependencies)` {/*usecallback*/}
Call `useCallback` at the top level of your component to declare a memoized callback:
```js {4,9}
import { useCallback } from 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
```
[See more examples below.](#examples-rerendering)
#### Parameters {/*parameters*/}
* `fn`: The function value that you want to memoize. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On subsequent renders, React will return the same function again if the `dependencies` have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call the function. The function is returned to you so you can decide when and whether to call it.
* `dependencies`: The list of all reactive values referenced inside of the `fn` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm.
#### Returns {/*returns*/}
On the initial render, `useCallback` returns the `fn` function you have passed.
During subsequent renders, it will either return an already stored `fn` function from the last render (if the dependencies haven't changed), or return the `fn` function you have passed during this render.
#### Caveats {/*caveats*/}
* `useCallback` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* React **will not throw away the cached function unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache--for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useCallback` as a performance optimization. Otherwise, a [state variable](/apis/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead) or a [ref](/apis/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
## Usage {/*usage*/}
### Skipping re-rendering of components {/*skipping-re-rendering-of-components*/}
@ -765,45 +804,6 @@ This ensures that the consumers of your Hook can optimize their own code when ne
---
## Reference {/*reference*/}
### `useCallback(fn, dependencies)` {/*usecallback*/}
Call `useCallback` at the top level of your component to declare a memoized callback:
```js {4,9}
import { useCallback } from 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
```
[See more examples above.](#examples-rerendering)
#### Parameters {/*parameters*/}
* `fn`: The function value that you want to memoize. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On subsequent renders, React will return the same function again if the `dependencies` have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call the function. The function is returned to you so you can decide when and whether to call it.
* `dependencies`: The list of all reactive values referenced inside of the `fn` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm.
#### Returns {/*returns*/}
On the initial render, `useCallback` returns the `fn` function you have passed.
During subsequent renders, it will either return an already stored `fn` function from the last render (if the dependencies haven't changed), or return the `fn` function you have passed during this render.
#### Caveats {/*caveats*/}
* `useCallback` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* React **will not throw away the cached function unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache--for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useCallback` as a performance optimization. Otherwise, a [state variable](/apis/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead) or a [ref](/apis/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
## Troubleshooting {/*troubleshooting*/}
### Every time my component renders, `useCallback` returns a different function {/*every-time-my-component-renders-usecallback-returns-a-different-function*/}

64
beta/src/content/apis/react/useContext.md

@ -16,6 +16,38 @@ const value = useContext(SomeContext)
---
## Reference {/*reference*/}
### `useContext(SomeContext)` {/*usecontext*/}
Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context)
```js
import { useContext } from 'react';
function MyComponent() {
const theme = useContext(ThemeContext);
// ...
```
[See more examples below.](#examples-basic)
#### Parameters {/*parameters*/}
* `SomeContext`: The context that you've previously created with [`createContext`](/apis/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components.
#### Returns {/*returns*/}
`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/apis/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
#### Caveats {/*caveats*/}
* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `<Context.Provider>` **needs to be *above*** the component doing the `useContext()` call.
* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/apis/react/memo) does not prevent the children receiving fresh context values from above.
* If your build system produces duplicates modules in the output (which can happen if you use symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison.
---
## Usage {/*usage*/}
@ -1309,38 +1341,6 @@ As a result of this change, even if `MyApp` needs to re-render, the components c
---
## Reference {/*reference*/}
### `useContext(SomeContext)` {/*usecontext*/}
Call `useContext` at the top level of your component to read and subscribe to [context.](/learn/passing-data-deeply-with-context)
```js
import { useContext } from 'react';
function MyComponent() {
const theme = useContext(ThemeContext);
// ...
```
[See more examples above.](#examples-basic)
#### Parameters {/*parameters*/}
* `SomeContext`: The context that you've previously created with [`createContext`](/apis/react/createContext). The context itself does not hold the information, it only represents the kind of information you can provide or read from components.
#### Returns {/*returns*/}
`useContext` returns the context value for the calling component. It is determined as the `value` passed to the closest `SomeContext.Provider` above the calling component in the tree. If there is no such provider, then the returned value will be the `defaultValue` you have passed to [`createContext`](/apis/react/createContext) for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
#### Caveats {/*caveats*/}
* `useContext()` call in a component is not affected by providers returned from the *same* component. The corresponding `<Context.Provider>` **needs to be *above*** the component doing the `useContext()` call.
* React **automatically re-renders** all the children that use a particular context starting from the provider that receives a different `value`. The previous and the next values are compared with the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Skipping re-renders with [`memo`](/apis/react/memo) does not prevent the children receiving fresh context values from above.
* If your build system produces duplicates modules in the output (which can happen if you use symlinks), this can break context. Passing something via context only works if `SomeContext` that you use to provide context and `SomeContext` that you use to read it are ***exactly* the same object**, as determined by a `===` comparison.
---
## Troubleshooting {/*troubleshooting*/}
### My component doesn't see the value from my provider {/*my-component-doesnt-see-the-value-from-my-provider*/}

57
beta/src/content/apis/react/useDebugValue.md

@ -16,6 +16,33 @@ useDebugValue(value, format?)
---
## Reference {/*reference*/}
### `useDebugValue(value, format?)` {/*usedebugvalue*/}
Call `useDebugValue` at the top level of your [custom Hook](/learn/reusing-logic-with-custom-hooks) to display a readable debug value:
```js
import { useDebugValue } from 'react';
function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `value`: The value you want to display in React DevTools. It can have any type.
* **optional** `format`: A formatting function. When the component is inspected, React DevTools will call the formatting function with the `value` as the argument, and then display the returned formatted value (which may have any type). If you don't specify the formatting function, the original `value` itself will be displayed.
#### Returns {/*returns*/}
`useDebugValue` does not return anything.
## Usage {/*usage*/}
### Adding a label to a custom Hook {/*adding-a-label-to-a-custom-hook*/}
@ -93,33 +120,3 @@ useDebugValue(date, date => date.toDateString());
Your formatting function will receive the <CodeStep step={1}>debug value</CodeStep> as a parameter and should return a <CodeStep step={2}>formatted display value</CodeStep>. When your component is inspected, React DevTools will call the formatting function and display its result.
This lets you avoid running potentially expensive formatting logic unless the component is actually inspected. For example, if `date` is a Date value, this avoids calling `toDateString()` on it for every render of your component.
---
## Reference {/*reference*/}
### `useDebugValue(value, format?)` {/*usedebugvalue*/}
Call `useDebugValue` at the top level of your [custom Hook](/learn/reusing-logic-with-custom-hooks) to display a readable debug value:
```js
import { useDebugValue } from 'react';
function useOnlineStatus() {
// ...
useDebugValue(isOnline ? 'Online' : 'Offline');
// ...
}
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `value`: The value you want to display in React DevTools. It can have any type.
* **optional** `format`: A formatting function. When the component is inspected, React DevTools will call the formatting function with the `value` as the argument, and then display the returned formatted value (which may have any type). If you don't specify the formatting function, the original `value` itself will be displayed.
#### Returns {/*returns*/}
`useDebugValue` does not return anything.

86
beta/src/content/apis/react/useDeferredValue.md

@ -16,6 +16,48 @@ const deferredValue = useDeferredValue(value)
---
## Reference {/*reference*/}
### `useDeferredValue(value)` {/*usedeferredvalue*/}
Call `useDeferredValue` at the top level of your component to get a deferred version of that value.
```js
import { useState, useDeferredValue } from 'react';
function SearchPage() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// ...
}
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `value`: The value you want to defer. It can have any type.
#### Returns {/*returns*/}
During the initial render, the returned deferred value will be the same as the value you provided. During updates, React will first attempt a re-render with the old value (so the returned value will match the old value), and then try another re-render in background with the new value (so the returned value will match the updated value).
#### Caveats {/*caveats*/}
- The values you pass to `useDeferredValue` should either be primitive values (like strings and numbers) or objects created outside of rendering. If you create a new object during rendering and immediately pass it to `useDeferredValue`, it will be different on every render, causing unnecessary background re-renders.
- When `useDeferredValue` receives a different value (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), in addition to the current render (when it still uses the previous value), it schedules a re-render in the background with the new value. The background re-render is interruptible: if there's another update to the `value`, React will restart the background re-render from scratch. For example, if the user is typing into an input faster than a chart receiving its deferred value can re-render, the chart will only re-render after the user stops typing.
- `useDeferredValue` is integrated with [`<Suspense>`.](/apis/react/Suspense) If the background update caused by a new value suspends the UI, the user will not see the fallback. They will keep seeing the old deferred value until the data loads.
- `useDeferredValue` does not by itself prevent extra network requests.
- There is no fixed delay caused by `useDeferredValue` itself. As soon as React finishes the original re-render, React will immediately start working on the background re-render with the new deferred value. However, any updates caused by events (like typing) will interrupt the background re-render and get prioritized over it.
- The background re-render caused by `useDeferredValue` does not fire Effects until it's committed to the screen. If the background re-render suspends, its Effects will run after the data loads and the UI updates.
---
## Usage {/*usage*/}
### Showing stale content while fresh content is loading {/*showing-stale-content-while-fresh-content-is-loading*/}
@ -914,47 +956,3 @@ Also, unlike with debouncing or throttling, deferred re-renders done by `useDefe
If the work you're optimizing doesn't happen during rendering, debouncing and throttling are still useful. For example, they can let you fire fewer network requests. You can also use these techniques together.
</DeepDive>
---
## Reference {/*reference*/}
### `useDeferredValue(value)` {/*usedeferredvalue*/}
Call `useDeferredValue` at the top level of your component to get a deferred version of that value.
```js
import { useState, useDeferredValue } from 'react';
function SearchPage() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
// ...
}
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `value`: The value you want to defer. It can have any type.
#### Returns {/*returns*/}
During the initial render, the returned deferred value will be the same as the value you provided. During updates, React will first attempt a re-render with the old value (so the returned value will match the old value), and then try another re-render in background with the new value (so the returned value will match the updated value).
#### Caveats {/*caveats*/}
- The values you pass to `useDeferredValue` should either be primitive values (like strings and numbers) or objects created outside of rendering. If you create a new object during rendering and immediately pass it to `useDeferredValue`, it will be different on every render, causing unnecessary background re-renders.
- When `useDeferredValue` receives a different value (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), in addition to the current render (when it still uses the previous value), it schedules a re-render in the background with the new value. The background re-render is interruptible: if there's another update to the `value`, React will restart the background re-render from scratch. For example, if the user is typing into an input faster than a chart receiving its deferred value can re-render, the chart will only re-render after the user stops typing.
- `useDeferredValue` is integrated with [`<Suspense>`.](/apis/react/Suspense) If the background update caused by a new value suspends the UI, the user will not see the fallback. They will keep seeing the old deferred value until the data loads.
- `useDeferredValue` does not by itself prevent extra network requests.
- There is no fixed delay caused by `useDeferredValue` itself. As soon as React finishes the original re-render, React will immediately start working on the background re-render with the new deferred value. However, any updates caused by events (like typing) will interrupt the background re-render and get prioritized over it.
- The background re-render caused by `useDeferredValue` does not fire Effects until it's committed to the screen. If the background re-render suspends, its Effects will run after the data loads and the UI updates.

108
beta/src/content/apis/react/useEffect.md

@ -16,6 +16,60 @@ useEffect(setup, dependencies?)
---
## Reference {/*reference*/}
### `useEffect(setup, dependencies?)` {/*useeffect*/}
Call `useEffect` at the top level of your component to declare an Effect:
```js
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
```
[See more examples below.](#examples-connecting)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component. [See the difference between passing an array of dependencies, an empty array, and no dependencies at all.](#examples-dependencies)
#### Returns {/*returns*/}
`useEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* `useEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* If you're **not trying to synchronize with some external system,** [you probably don't need an Effect.](/learn/you-might-not-need-an-effect)
* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [you need to implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](#removing-unnecessary-object-dependencies) and [function](#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
* If your Effect wasn't caused by an interaction (like a click), React will let the browser **paint the updated screen first before running your Effect.** If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Even if your Effect was caused by an interaction (like a click), **the browser may repaint the screen before processing the state updates inside your Effect.** Usually, that's what you want. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Effects **only run on the client.** They don't run during server rendering.
---
## Usage {/*usage*/}
### Connecting to an external system {/*connecting-to-an-external-system*/}
@ -1703,60 +1757,6 @@ Use this pattern sparingly. Keep in mind that users with a slow connection will
---
## Reference {/*reference*/}
### `useEffect(setup, dependencies?)` {/*useeffect*/}
Call `useEffect` at the top level of your component to declare an Effect:
```js
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
```
[See more examples above.](#examples-connecting)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component. [See the difference between passing an array of dependencies, an empty array, and no dependencies at all.](#examples-dependencies)
#### Returns {/*returns*/}
`useEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* `useEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* If you're **not trying to synchronize with some external system,** [you probably don't need an Effect.](/learn/you-might-not-need-an-effect)
* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [you need to implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](#removing-unnecessary-object-dependencies) and [function](#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
* If your Effect wasn't caused by an interaction (like a click), React will let the browser **paint the updated screen first before running your Effect.** If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Even if your Effect was caused by an interaction (like a click), **the browser may repaint the screen before processing the state updates inside your Effect.** Usually, that's what you want. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with [`useLayoutEffect`.](/apis/react/useLayoutEffect)
* Effects **only run on the client.** They don't run during server rendering.
---
## Troubleshooting {/*troubleshooting*/}
### My Effect runs twice when the component mounts {/*my-effect-runs-twice-when-the-component-mounts*/}

63
beta/src/content/apis/react/useId.md

@ -16,6 +16,38 @@ const id = useId()
---
## Reference {/*reference*/}
### `useId()` {/*useid*/}
Call `useId` at the top level of your component to generate a unique ID:
```js
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
`useId` does not take any parameters.
#### Returns {/*returns*/}
`useId` returns a unique ID string associated with this particular `useId` call in this particular component.
#### Caveats {/*caveats*/}
* `useId` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* `useId` **should not be used to generate keys** in a list. [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)
---
## Usage {/*usage*/}
<Pitfall>
@ -271,34 +303,3 @@ input { margin: 5px; }
</Sandpack>
---
## Reference {/*reference*/}
### `useId()` {/*useid*/}
Call `useId` at the top level of your component to generate a unique ID:
```js
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
`useId` does not take any parameters.
#### Returns {/*returns*/}
`useId` returns a unique ID string associated with this particular `useId` call in this particular component.
#### Caveats {/*caveats*/}
* `useId` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* `useId` **should not be used to generate keys** in a list. [Keys should be generated from your data.](/learn/rendering-lists#where-to-get-your-key)

68
beta/src/content/apis/react/useImperativeHandle.md

@ -16,6 +16,40 @@ useImperativeHandle(ref, createHandle, dependencies?)
---
## Reference {/*reference*/}
### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
```js
import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
};
}, []);
// ...
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/apis/react/forwardRef#render-function)
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. The ref handle you return have any type. Usually, you will return an object with the methods you want to expose.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If a re-render resulted in a change to some dependency, or if you did not specify the dependencies at all, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
#### Returns {/*returns*/}
`useImperativeHandle` returns `undefined`.
---
## Usage {/*usage*/}
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
@ -252,37 +286,3 @@ export default AddComment;
**If you can express something as a prop, you should not use a ref.** For example, instead of exposing an imperative handle like `{ open, close }` from a `Modal` component, it is better to take `isOpen` as a prop like `<Modal isOpen={isOpen} />`. [Effects](/learn/synchronizing-with-effects) can help you expose imperative behaviors via props.
</Pitfall>
---
## Reference {/*reference*/}
### `useImperativeHandle(ref, createHandle, dependencies?)` {/*useimperativehandle*/}
Call `useImperativeHandle` at the top level of your component to customize the ref handle it exposes:
```js
import { forwardRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
useImperativeHandle(ref, () => {
return {
// ... your methods ...
};
}, []);
// ...
```
[See more examples.](#usage)
#### Parameters {/*parameters*/}
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/apis/react/forwardRef#render-function)
* `createHandle`: A function that takes no arguments and returns the ref handle you want to expose. The ref handle you return have any type. Usually, you will return an object with the methods you want to expose.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `createHandle` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If a re-render resulted in a change to some dependency, or if you did not specify the dependencies at all, your `createHandle` function will re-execute, and the newly created handle will be assigned to the ref.
#### Returns {/*returns*/}
`useImperativeHandle` returns `undefined`.

88
beta/src/content/apis/react/useInsertionEffect.md

@ -22,6 +22,50 @@ useInsertionEffect(setup, dependencies?)
---
## Reference {/*reference*/}
### `useInsertionEffect(setup, dependencies?)` {/*useinsertioneffect*/}
<Pitfall>
`useInsertionEffect` is aimed at CSS-in-JS library authors. Unless you are working on a CSS-in-JS library and need a place to inject the styles, you probably want [`useEffect`](/apis/react/useEffect) or [`useLayoutEffect`](/apis/react/useLayoutEffect) instead.
</Pitfall>
Call `useInsertionEffect` to insert the styles before any DOM mutations:
```js
function useCSS(rule) {
useInsertionEffect(() => {
// As explained earlier, we don't recommend runtime injection of <style> tags.
// But if you have to do it, then it's important to do in useInsertionEffect.
// ... inject <style> tags here ...
});
return rule;
}
```
[See more examples below.](#examples-connecting)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns {/*returns*/}
`useInsertionEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* Effects only run on the client. They don't run during server rendering.
* You can't update state from inside `useInsertionEffect`.
* By the time `useInsertionEffect` runs, refs are not attached yet, and DOM is not yet updated.
---
## Usage {/*usage*/}
### Injecting dynamic styles from CSS-in-JS libraries {/*injecting-dynamic-styles-from-css-in-js-libraries*/}
@ -99,47 +143,3 @@ If you insert styles during rendering and React is processing a [non-blocking up
`useInsertionEffect` is better than inserting styles during [`useLayoutEffect`](/apis/react/useLayoutEffect) or [`useEffect`](/apis/react/useEffect) because it ensures that by the time other Effects run in your components, the `<style>` tags have already been inserted. Otherwise, layout calculations in regular Effects would be wrong due to outdated styles.
</DeepDive>
---
## Reference {/*reference*/}
### `useInsertionEffect(setup, dependencies?)` {/*useinsertioneffect*/}
<Pitfall>
`useInsertionEffect` is aimed at CSS-in-JS library authors. Unless you are working on a CSS-in-JS library and need a place to inject the styles, you probably want [`useEffect`](/apis/react/useEffect) or [`useLayoutEffect`](/apis/react/useLayoutEffect) instead.
</Pitfall>
Call `useInsertionEffect` to insert the styles before any DOM mutations:
```js
function useCSS(rule) {
useInsertionEffect(() => {
// As explained earlier, we don't recommend runtime injection of <style> tags.
// But if you have to do it, then it's important to do in useInsertionEffect.
// ... inject <style> tags here ...
});
return rule;
}
```
[See more examples above.](#examples-connecting)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns {/*returns*/}
`useInsertionEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* Effects only run on the client. They don't run during server rendering.
* You can't update state from inside `useInsertionEffect`.
* By the time `useInsertionEffect` runs, refs are not attached yet, and DOM is not yet updated.

94
beta/src/content/apis/react/useLayoutEffect.md

@ -22,6 +22,53 @@ useLayoutEffect(setup, dependencies?)
---
## Reference {/*reference*/}
### `useLayoutEffect(setup, dependencies?)` {/*useinsertioneffect*/}
Call `useLayoutEffect` perform the layout measurements before the browser repaints the screen:
```js
import { useState, useRef, useLayoutEffect } from 'react';
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);
// ...
```
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns {/*returns*/}
`useLayoutEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* `useLayoutEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [you need to implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](/apis/react/useEffect#removing-unnecessary-object-dependencies) and [function](/apis/react/useEffect#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](/apis/react/useEffect#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](/apis/react/useEffect#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
* Effects **only run on the client.** They don't run during server rendering.
* The code inside `useLayoutEffect` and all state updates scheduled from it **block the browser from repainting the screen.** When used excessively, this can make your app very slow. When possible, prefer [`useEffect`.](/apis/reac/useEffect)
---
## Usage {/*usage*/}
### Measuring layout before the browser repaints the screen {/*measuring-layout-before-the-browser-repaints-the-screen*/}
@ -663,53 +710,6 @@ Rendering in two passes and blocking the browser hurts performance. Try to avoid
---
## Reference {/*reference*/}
### `useLayoutEffect(setup, dependencies?)` {/*useinsertioneffect*/}
Call `useLayoutEffect` perform the layout measurements before the browser repaints the screen:
```js
import { useState, useRef, useLayoutEffect } from 'react';
function Tooltip() {
const ref = useRef(null);
const [tooltipHeight, setTooltipHeight] = useState(0);
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setTooltipHeight(height);
}, []);
// ...
```
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is first added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function one last time.
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
#### Returns {/*returns*/}
`useLayoutEffect` returns `undefined`.
#### Caveats {/*caveats*/}
* `useLayoutEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [you need to implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](/apis/react/useEffect#removing-unnecessary-object-dependencies) and [function](/apis/react/useEffect#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](/apis/react/useEffect#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](/apis/react/useEffect#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
* Effects **only run on the client.** They don't run during server rendering.
* The code inside `useLayoutEffect` and all state updates scheduled from it **block the browser from repainting the screen.** When used excessively, this can make your app very slow. When possible, prefer [`useEffect`.](/apis/reac/useEffect)
---
## Troubleshooting {/*troubleshooting*/}
### I'm getting an error: "`useLayoutEffect` does nothing on the server" {/*im-getting-an-error-uselayouteffect-does-nothing-on-the-server*/}

80
beta/src/content/apis/react/useMemo.md

@ -16,6 +16,46 @@ const cachedValue = useMemo(calculateValue, dependencies)
---
## Reference {/*reference*/}
### `useMemo(calculateValue, dependencies)` {/*usememo*/}
Call `useMemo` at the top level of your component to declare a memoized value:
```js
import { useMemo } from 'react';
function TodoList({ todos, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
// ...
}
```
[See more examples below.](#examples-recalculation)
#### Parameters {/*parameters*/}
* `calculateValue`: The function calculating the value that you want to memoize. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On subsequent renders, React will return the same value again if the `dependencies` have not changed since the last render. Otherwise, it will call `calculateValue`, return its result, and store it in case it can be reused later.
* `dependencies`: The list of all reactive values referenced inside of the `calculateValue` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm.
#### Returns {/*returns*/}
On the initial render, `useMemo` returns the result of calling `calculateValue` with no arguments.
During subsequent renders, it will either return an already stored value from the last render (if the dependencies haven't changed), or call `calculateValue` again, and return the result that `calculateValue` has returned.
#### Caveats {/*caveats*/}
* `useMemo` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your calculation function twice** in order to [help you find accidental impurities.](#my-calculation-runs-twice-on-every-re-render) This is development-only behavior and does not affect production. If your calculation function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
* React **will not throw away the cached value unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache--for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useMemo` solely as a performance optimization. Otherwise, a [state variable](/apis/react/useState#avoiding-recreating-the-initial-state) or a [ref](/apis/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
## Usage {/*usage*/}
### Skipping expensive recalculations {/*skipping-expensive-recalculations*/}
@ -1109,46 +1149,6 @@ The two examples above are completely equivalent. The only benefit to `useCallba
---
## Reference {/*reference*/}
### `useMemo(calculateValue, dependencies)` {/*usememo*/}
Call `useMemo` at the top level of your component to declare a memoized value:
```js
import { useMemo } from 'react';
function TodoList({ todos, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
// ...
}
```
[See more examples above.](#examples-recalculation)
#### Parameters {/*parameters*/}
* `calculateValue`: The function calculating the value that you want to memoize. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On subsequent renders, React will return the same value again if the `dependencies` have not changed since the last render. Otherwise, it will call `calculateValue`, return its result, and store it in case it can be reused later.
* `dependencies`: The list of all reactive values referenced inside of the `calculateValue` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm.
#### Returns {/*returns*/}
On the initial render, `useMemo` returns the result of calling `calculateValue` with no arguments.
During subsequent renders, it will either return an already stored value from the last render (if the dependencies haven't changed), or call `calculateValue` again, and return the result that `calculateValue` has returned.
#### Caveats {/*caveats*/}
* `useMemo` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your calculation function twice** in order to [help you find accidental impurities.](#my-calculation-runs-twice-on-every-re-render) This is development-only behavior and does not affect production. If your calculation function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
* React **will not throw away the cached value unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache--for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useMemo` solely as a performance optimization. Otherwise, a [state variable](/apis/react/useState#avoiding-recreating-the-initial-state) or a [ref](/apis/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
## Troubleshooting {/*troubleshooting*/}
### My calculation runs twice on every re-render {/*my-calculation-runs-twice-on-every-re-render*/}

144
beta/src/content/apis/react/useReducer.md

@ -16,6 +16,78 @@ const [state, dispatch] = useReducer(reducer, initialArg, init?)
---
## Reference {/*reference*/}
### `useReducer(reducer, initialArg, init?)` {/*usereducer*/}
Call `useReducer` at the top level of your component to manage its state with a [reducer.](/learn/extracting-state-logic-into-a-reducer)
```js
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
```
[See more examples below.](#examples-basic)
#### Parameters {/*parameters*/}
* `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types.
* `initialArg`: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next `init` argument.
* **optional** `init`: The initializer function that specifies how the initial state is calculated. If it's not specified, the initial state is set to `initialArg`. Otherwise, the initial state is set to the result of calling `init(initialArg)`.
#### Returns {/*returns*/}
`useReducer` returns an array with exactly two values:
1. The current state. During the first render, it's set to `init(initialArg)` or `initialArg` (if there's no `init`).
2. The [`dispatch` function](#dispatch) that lets you update the state to a different value and trigger a re-render.
#### Caveats {/*caveats*/}
* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect the logic of your component. The result from one of the calls is ignored.
---
### `dispatch` function {/*dispatch*/}
The `dispatch` function returned by `useReducer` lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the `dispatch` function:
```js
const [state, dispatch] = useReducer(reducer, { age: 42 });
function handleClick() {
dispatch({ type: 'incremented_age' });
// ...
```
React will set the next state to the result of calling the `reducer` function you've provided with the current `state` and the action you've passed to `dispatch`.
#### Parameters {/*dispatch-parameters*/}
* `action`: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with a `type` property identifying it and, optionally, other properties with additional information.
#### Returns {/*dispatch-returns*/}
`dispatch` functions do not have a return value.
#### Caveats {/*setstate-caveats*/}
* The `dispatch` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `dispatch` function, [you will still get the old value](#ive-dispatched-an-action-but-logging-gives-me-the-old-state-value) that was on the screen before your call.
* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. React may still need to call your component before ignoring the result, but it shouldn't affect your code.
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/apis/react-dom/flushsync)
---
## Usage {/*usage*/}
### Adding a reducer to a component {/*adding-a-reducer-to-a-component*/}
@ -864,78 +936,6 @@ export default function TodoList({ username }) {
---
## Reference {/*reference*/}
### `useReducer(reducer, initialArg, init?)` {/*usereducer*/}
Call `useReducer` at the top level of your component to manage its state with a [reducer.](/learn/extracting-state-logic-into-a-reducer)
```js
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
```
[See more examples above.](#examples-basic)
#### Parameters {/*parameters*/}
* `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types.
* `initialArg`: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next `init` argument.
* **optional** `init`: The initializer function that specifies how the initial state is calculated. If it's not specified, the initial state is set to `initialArg`. Otherwise, the initial state is set to the result of calling `init(initialArg)`.
#### Returns {/*returns*/}
`useReducer` returns an array with exactly two values:
1. The current state. During the first render, it's set to `init(initialArg)` or `initialArg` (if there's no `init`).
2. The [`dispatch` function](#dispatch) that lets you update the state to a different value and trigger a re-render.
#### Caveats {/*caveats*/}
* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect the logic of your component. The result from one of the calls is ignored.
---
### `dispatch` function {/*dispatch*/}
The `dispatch` function returned by `useReducer` lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the `dispatch` function:
```js
const [state, dispatch] = useReducer(reducer, { age: 42 });
function handleClick() {
dispatch({ type: 'incremented_age' });
// ...
```
React will set the next state to the result of calling the `reducer` function you've provided with the current `state` and the action you've passed to `dispatch`.
#### Parameters {/*dispatch-parameters*/}
* `action`: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with a `type` property identifying it and, optionally, other properties with additional information.
#### Returns {/*dispatch-returns*/}
`dispatch` functions do not have a return value.
#### Caveats {/*setstate-caveats*/}
* The `dispatch` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `dispatch` function, [you will still get the old value](#ive-dispatched-an-action-but-logging-gives-me-the-old-state-value) that was on the screen before your call.
* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. React may still need to call your component before ignoring the result, but it shouldn't affect your code.
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/apis/react-dom/flushsync)
---
## Troubleshooting {/*troubleshooting*/}
### I've dispatched an action, but logging gives me the old state value {/*ive-dispatched-an-action-but-logging-gives-me-the-old-state-value*/}

76
beta/src/content/apis/react/useRef.md

@ -16,6 +16,44 @@ const ref = useRef(initialValue)
---
## Reference {/*reference*/}
### `useRef(initialValue)` {/*useref*/}
Call `useRef` at the top level of your component to declare a [ref.](/learn/referencing-values-with-refs)
```js
import { useRef } from 'react';
function MyComponent() {
const intervalRef = useRef(0);
const inputRef = useRef(null);
// ...
```
See examples of [referencing values](#examples-value) and [DOM manipulation.](#examples-dom)
#### Parameters {/*parameters*/}
* `initialValue`: The value you want the ref object's `current` property to be initially. It can be a value of any type. This argument is ignored after the initial render.
#### Returns {/*returns*/}
`useRef` returns an object with a single property:
* `current`: Initially, it's set to the `initialValue` you have passed. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property.
On the next renders, `useRef` will return the same object.
#### Caveats {/*caveats*/}
* You can mutate the `ref.current` property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn't mutate that object.
* When you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object.
* Do not write _or read_ `ref.current` during rendering, except for [initialization.](#avoiding-recreating-the-ref-contents) This makes your component's behavior unpredictable.
* In Strict Mode, React will **call your component function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. This means that each ref object will be created twice, and one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the logic of your component.
---
## Usage {/*usage*/}
### Referencing a value with a ref {/*referencing-a-value-with-a-ref*/}
@ -500,44 +538,6 @@ Here, the `playerRef` itself is nullable. However, you should be able to convinc
---
## Reference {/*reference*/}
### `useRef(initialValue)` {/*useref*/}
Call `useRef` at the top level of your component to declare a [ref.](/learn/referencing-values-with-refs)
```js
import { useRef } from 'react';
function MyComponent() {
const intervalRef = useRef(0);
const inputRef = useRef(null);
// ...
```
See examples of [referencing values](#examples-value) and [DOM manipulation.](#examples-dom)
#### Parameters {/*parameters*/}
* `initialValue`: The value you want the ref object's `current` property to be initially. It can be a value of any type. This argument is ignored after the initial render.
#### Returns {/*returns*/}
`useRef` returns an object with a single property:
* `current`: Initially, it's set to the `initialValue` you have passed. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property.
On the next renders, `useRef` will return the same object.
#### Caveats {/*caveats*/}
* You can mutate the `ref.current` property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn't mutate that object.
* When you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object.
* Do not write _or read_ `ref.current` during rendering, except for [initialization.](#avoiding-recreating-the-ref-contents) This makes your component's behavior unpredictable.
* In Strict Mode, React will **call your component function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. This means that each ref object will be created twice, and one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the logic of your component.
---
## Troubleshooting {/*troubleshooting*/}
### I can't get a ref to a custom component {/*i-cant-get-a-ref-to-a-custom-component*/}

150
beta/src/content/apis/react/useState.md

@ -16,6 +16,81 @@ const [state, setState] = useState(initialState)
---
## Reference {/*reference*/}
### `useState(initialState)` {/*usestate*/}
Call `useState` at the top level of your component to declare a [state variable.](/learn/state-a-components-memory)
```js
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
const [todos, setTodos] = useState(() => createTodos());
// ...
```
The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)
[See more examples below.](#examples-basic)
#### Parameters {/*parameters*/}
* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
* If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example above.](#avoiding-recreating-the-initial-state)
#### Returns {/*returns*/}
`useState` returns an array with exactly two values:
1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render.
#### Caveats {/*caveats*/}
* `useState` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
### `set` functions, like `setSomething(nextState)` {/*setstate*/}
The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state:
```js
const [name, setName] = useState('Edward');
function handleClick() {
setName('Taylor');
setAge(a => a + 1);
// ...
```
#### Parameters {/*setstate-parameters*/}
* `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions.
* If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example above.](#updating-state-based-on-the-previous-state)
#### Returns {/*setstate-returns*/}
`set` functions do not have a return value.
#### Caveats {/*setstate-caveats*/}
* The `set` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `set` function, [you will still get the old value](#ive-updated-the-state-but-logging-gives-me-the-old-value) that was on the screen before your call.
* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn't affect your code.
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/apis/react-dom/flushSync)
* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example above.](#storing-information-from-previous-renders)
* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
## Usage {/*usage*/}
### Adding state to a component {/*adding-state-to-a-component*/}
@ -1069,81 +1144,6 @@ This pattern can be hard to understand and is usually best avoided. However, it'
---
## Reference {/*reference*/}
### `useState(initialState)` {/*usestate*/}
Call `useState` at the top level of your component to declare a [state variable.](/learn/state-a-components-memory)
```js
import { useState } from 'react';
function MyComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
const [todos, setTodos] = useState(() => createTodos());
// ...
```
The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment)
[See more examples above.](#examples-basic)
#### Parameters {/*parameters*/}
* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
* If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example above.](#avoiding-recreating-the-initial-state)
#### Returns {/*returns*/}
`useState` returns an array with exactly two values:
1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render.
#### Caveats {/*caveats*/}
* `useState` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
* In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
### `set` functions, like `setSomething(nextState)` {/*setstate*/}
The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state:
```js
const [name, setName] = useState('Edward');
function handleClick() {
setName('Taylor');
setAge(a => a + 1);
// ...
```
#### Parameters {/*setstate-parameters*/}
* `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions.
* If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example above.](#updating-state-based-on-the-previous-state)
#### Returns {/*setstate-returns*/}
`set` functions do not have a return value.
#### Caveats {/*setstate-caveats*/}
* The `set` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `set` function, [you will still get the old value](#ive-updated-the-state-but-logging-gives-me-the-old-value) that was on the screen before your call.
* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn't affect your code.
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/apis/react-dom/flushSync)
* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example above.](#storing-information-from-previous-renders)
* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
---
## Troubleshooting {/*troubleshooting*/}
### I've updated the state, but logging gives me the old value {/*ive-updated-the-state-but-logging-gives-me-the-old-value*/}

86
beta/src/content/apis/react/useSyncExternalStore.md

@ -16,6 +16,49 @@ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?
---
## Reference {/*reference*/}
### `useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)` {/*usesyncexternalstore*/}
Call `useSyncExternalStore` at the top level of your component to read a value from an external data store.
```js
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
// ...
}
```
It returns the snapshot of the data in the store. You need to pass two functions as arguments:
1. The `subscribe` function should subscribe to the store and return a function that unsubscribes.
2. The `getSnapshot` function should read a snapshot of the data from the store.
[See more examples below.](#usage)
#### Parameters {/*parameters*/}
* `subscribe`: A function that takes a single `callback` argument and subscribes it to the store. When the store changes, it should invoke the provided `callback`. This will cause the component to re-render. The `subscribe` function should return a function that cleans up the subscription.
* `getSnapshot`: A function that returns a snapshot of the data in the store that's needed by the component. While the store has not changed, repeated calls to `getSnapshot` must return the same value. If the store changes and the returned value is different (as compared by [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), React will re-render the component.
* **optional** `getServerSnapshot`: A function that returns the initial snapshot of the data in the store. It will be used only during server rendering and during hydration of server-rendered content on the client. The server snapshot must be the same between the client and the server, and is usually serialized and passed from the server to the client. If this function is not provided, rendering the component on the server will throw an error.
#### Returns {/*returns*/}
The current snapshot of the store which you can use in your rendering logic.
#### Caveats {/*caveats*/}
* The store snapshot returned by `getSnapshot` must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.
* If a different `subscribe` function is passed during a re-render, React will re-subscribe to the store using the newly passed `subscribe` function. You can prevent this by declaring `subscribe` outside the component.
---
## Usage {/*usage*/}
### Subscribing to an external store {/*subscribing-to-an-external-store*/}
@ -306,49 +349,6 @@ Make sure that `getServerSnapshot` returns the same exact data on the initial cl
---
## Reference {/*reference*/}
### `useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)` {/*usesyncexternalstore*/}
Call `useSyncExternalStore` at the top level of your component to read a value from an external data store.
```js
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
// ...
}
```
It returns the snapshot of the data in the store. You need to pass two functions as arguments:
1. The `subscribe` function should subscribe to the store and return a function that unsubscribes.
2. The `getSnapshot` function should read a snapshot of the data from the store.
[See more examples above.](#usage)
#### Parameters {/*parameters*/}
* `subscribe`: A function that takes a single `callback` argument and subscribes it to the store. When the store changes, it should invoke the provided `callback`. This will cause the component to re-render. The `subscribe` function should return a function that cleans up the subscription.
* `getSnapshot`: A function that returns a snapshot of the data in the store that's needed by the component. While the store has not changed, repeated calls to `getSnapshot` must return the same value. If the store changes and the returned value is different (as compared by [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), React will re-render the component.
* **optional** `getServerSnapshot`: A function that returns the initial snapshot of the data in the store. It will be used only during server rendering and during hydration of server-rendered content on the client. The server snapshot must be the same between the client and the server, and is usually serialized and passed from the server to the client. If this function is not provided, rendering the component on the server will throw an error.
#### Returns {/*returns*/}
The current snapshot of the store which you can use in your rendering logic.
#### Caveats {/*caveats*/}
* The store snapshot returned by `getSnapshot` must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.
* If a different `subscribe` function is passed during a re-render, React will re-subscribe to the store using the newly passed `subscribe` function. You can prevent this by declaring `subscribe` outside the component.
---
## Troubleshooting {/*troubleshooting*/}
### I'm getting an error: "The result of `getSnapshot` should be cached" {/*im-getting-an-error-the-result-of-getsnapshot-should-be-cached*/}

144
beta/src/content/apis/react/useTransition.md

@ -16,6 +16,78 @@ const [isPending, startTransition] = useTransition()
---
## Reference {/*reference*/}
### `useTransition()` {/*usetransition*/}
Call `useTransition` at the top level of your component to mark some state updates as transitions.
```js
import { useTransition } from 'react';
function TabContainer() {
const [isPending, startTransition] = useTransition();
// ...
}
```
[See more examples below.](/#usage)
#### Parameters {/*parameters*/}
`useTransition` does not take any parameters.
#### Returns {/*returns*/}
`useTransition` returns an array with exactly two items:
1. The `isPending` flag that tells you whether there is a pending transition.
2. The [`startTransition` function](#starttransition) that lets you mark a state update as a transition.
---
### `startTransition` function {/*starttransition*/}
The `startTransition` function returned by `useTransition` lets you mark a state update as a transition.
```js {6,8}
function TabContainer() {
const [isPending, startTransition] = useTransition();
const [tab, setTab] = useState('about');
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
// ...
}
```
#### Parameters {/*starttransition-parameters*/}
* `scope`: A function that updates some state by calling one or more [`set` functions.](/apis/react/useState#setstate) React immediately calls `scope` with no parameters and marks all state updates scheduled synchronously during the `scope` function call as transitions. They will be [non-blocking](#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](#preventing-unwanted-loading-indicators)
#### Returns {/*starttransition-returns*/}
`startTransition` does not return anything.
#### Caveats {/*starttransition-caveats*/}
* `useTransition` is a Hook, so it can only be called inside components or custom Hooks. If you need to start a transition somewhere else (for example, from a data library), call the standalone [`startTransition`](/apis/react/startTransition) instead.
* You can wrap an update into a transition only if you have access to the `set` function of that state. If you want to start a transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](/apis/react/useDeferredValue) instead.
* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as transitions.
* A state update marked as a transition will be interrupted by other state updates. For example, if you update a chart component inside a transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update.
* Transition updates can't be used to control text inputs.
* If there are multiple ongoing transitions, React currently batches them together. This is a limitation that will likely be removed in a future release.
---
## Usage {/*usage*/}
### Marking a state update as a non-blocking transition {/*marking-a-state-update-as-a-non-blocking-transition*/}
@ -1429,78 +1501,6 @@ main {
---
## Reference {/*reference*/}
### `useTransition()` {/*usetransition*/}
Call `useTransition` at the top level of your component to mark some state updates as transitions.
```js
import { useTransition } from 'react';
function TabContainer() {
const [isPending, startTransition] = useTransition();
// ...
}
```
[See more examples above.](/#usage)
#### Parameters {/*parameters*/}
`useTransition` does not take any parameters.
#### Returns {/*returns*/}
`useTransition` returns an array with exactly two items:
1. The `isPending` flag that tells you whether there is a pending transition.
2. The [`startTransition` function](#starttransition) that lets you mark a state update as a transition.
---
### `startTransition` function {/*starttransition*/}
The `startTransition` function returned by `useTransition` lets you mark a state update as a transition.
```js {6,8}
function TabContainer() {
const [isPending, startTransition] = useTransition();
const [tab, setTab] = useState('about');
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
// ...
}
```
#### Parameters {/*starttransition-parameters*/}
* `scope`: A function that updates some state by calling one or more [`set` functions.](/apis/react/useState#setstate) React immediately calls `scope` with no parameters and marks all state updates scheduled synchronously during the `scope` function call as transitions. They will be [non-blocking](#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](#preventing-unwanted-loading-indicators)
#### Returns {/*starttransition-returns*/}
`startTransition` does not return anything.
#### Caveats {/*starttransition-caveats*/}
* `useTransition` is a Hook, so it can only be called inside components or custom Hooks. If you need to start a transition somewhere else (for example, from a data library), call the standalone [`startTransition`](/apis/react/startTransition) instead.
* You can wrap an update into a transition only if you have access to the `set` function of that state. If you want to start a transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](/apis/react/useDeferredValue) instead.
* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as transitions.
* A state update marked as a transition will be interrupted by other state updates. For example, if you update a chart component inside a transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update.
* Transition updates can't be used to control text inputs.
* If there are multiple ongoing transitions, React currently batches them together. This is a limitation that will likely be removed in a future release.
---
## Troubleshooting {/*troubleshooting*/}
### Updating an input in a transition doesn't work {/*updating-an-input-in-a-transition-doesnt-work*/}

Loading…
Cancel
Save