Browse Source

[Beta] APIs -> Reference (#5400)

* [Beta] APIs -> Reference

* oops
main
dan 2 years ago
committed by GitHub
parent
commit
c79307666b
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      beta/src/components/Layout/Footer.tsx
  2. 18
      beta/src/components/Layout/Nav/Nav.tsx
  3. 6
      beta/src/components/Layout/Page.tsx
  4. 2
      beta/src/components/MDX/HomepageHero.tsx
  5. 43
      beta/src/content/apis/react-dom/index.md
  6. 21
      beta/src/content/apis/react/apis.md
  7. 20
      beta/src/content/apis/react/components.md
  8. 34
      beta/src/content/apis/react/legacy.md
  9. 2
      beta/src/content/learn/add-react-to-a-website.md
  10. 2
      beta/src/content/learn/adding-interactivity.md
  11. 4
      beta/src/content/learn/index.md
  12. 4
      beta/src/content/learn/keeping-components-pure.md
  13. 4
      beta/src/content/learn/lifecycle-of-reactive-effects.md
  14. 4
      beta/src/content/learn/manipulating-the-dom-with-refs.md
  15. 2
      beta/src/content/learn/reacting-to-input-with-state.md
  16. 4
      beta/src/content/learn/removing-effect-dependencies.md
  17. 2
      beta/src/content/learn/render-and-commit.md
  18. 2
      beta/src/content/learn/rendering-lists.md
  19. 8
      beta/src/content/learn/reusing-logic-with-custom-hooks.md
  20. 2
      beta/src/content/learn/separating-events-from-effects.md
  21. 6
      beta/src/content/learn/state-a-components-memory.md
  22. 16
      beta/src/content/learn/synchronizing-with-effects.md
  23. 2
      beta/src/content/learn/thinking-in-react.md
  24. 2
      beta/src/content/learn/tutorial-tic-tac-toe.md
  25. 2
      beta/src/content/learn/updating-objects-in-state.md
  26. 2
      beta/src/content/learn/writing-markup-with-jsx.md
  27. 12
      beta/src/content/learn/you-might-not-need-an-effect.md
  28. 22
      beta/src/content/reference/react-dom/client/createRoot.md
  29. 18
      beta/src/content/reference/react-dom/client/hydrateRoot.md
  30. 4
      beta/src/content/reference/react-dom/client/index.md
  31. 18
      beta/src/content/reference/react-dom/components/common.md
  32. 20
      beta/src/content/reference/react-dom/components/index.md
  33. 16
      beta/src/content/reference/react-dom/components/input.md
  34. 12
      beta/src/content/reference/react-dom/components/option.md
  35. 2
      beta/src/content/reference/react-dom/components/progress.md
  36. 12
      beta/src/content/reference/react-dom/components/select.md
  37. 14
      beta/src/content/reference/react-dom/components/textarea.md
  38. 4
      beta/src/content/reference/react-dom/createPortal.md
  39. 16
      beta/src/content/reference/react-dom/findDOMNode.md
  40. 0
      beta/src/content/reference/react-dom/flushSync.md
  41. 16
      beta/src/content/reference/react-dom/hydrate.md
  42. 43
      beta/src/content/reference/react-dom/index.md
  43. 20
      beta/src/content/reference/react-dom/render.md
  44. 12
      beta/src/content/reference/react-dom/server/index.md
  45. 14
      beta/src/content/reference/react-dom/server/renderToNodeStream.md
  46. 22
      beta/src/content/reference/react-dom/server/renderToPipeableStream.md
  47. 22
      beta/src/content/reference/react-dom/server/renderToReadableStream.md
  48. 4
      beta/src/content/reference/react-dom/server/renderToStaticMarkup.md
  49. 4
      beta/src/content/reference/react-dom/server/renderToStaticNodeStream.md
  50. 14
      beta/src/content/reference/react-dom/server/renderToString.md
  51. 4
      beta/src/content/reference/react-dom/unmountComponentAtNode.md
  52. 8
      beta/src/content/reference/react/Children.md
  53. 68
      beta/src/content/reference/react/Component.md
  54. 0
      beta/src/content/reference/react/Fragment.md
  55. 2
      beta/src/content/reference/react/Profiler.md
  56. 14
      beta/src/content/reference/react/PureComponent.md
  57. 16
      beta/src/content/reference/react/StrictMode.md
  58. 20
      beta/src/content/reference/react/Suspense.md
  59. 21
      beta/src/content/reference/react/apis.md
  60. 8
      beta/src/content/reference/react/cloneElement.md
  61. 20
      beta/src/content/reference/react/components.md
  62. 14
      beta/src/content/reference/react/createContext.md
  63. 4
      beta/src/content/reference/react/createElement.md
  64. 4
      beta/src/content/reference/react/createFactory.md
  65. 16
      beta/src/content/reference/react/createRef.md
  66. 8
      beta/src/content/reference/react/forwardRef.md
  67. 40
      beta/src/content/reference/react/index.md
  68. 8
      beta/src/content/reference/react/isValidElement.md
  69. 8
      beta/src/content/reference/react/lazy.md
  70. 34
      beta/src/content/reference/react/legacy.md
  71. 8
      beta/src/content/reference/react/memo.md
  72. 10
      beta/src/content/reference/react/startTransition.md
  73. 32
      beta/src/content/reference/react/useCallback.md
  74. 16
      beta/src/content/reference/react/useContext.md
  75. 0
      beta/src/content/reference/react/useDebugValue.md
  76. 12
      beta/src/content/reference/react/useDeferredValue.md
  77. 18
      beta/src/content/reference/react/useEffect.md
  78. 0
      beta/src/content/reference/react/useEffectEvent.md
  79. 6
      beta/src/content/reference/react/useId.md
  80. 6
      beta/src/content/reference/react/useImperativeHandle.md
  81. 10
      beta/src/content/reference/react/useInsertionEffect.md
  82. 20
      beta/src/content/reference/react/useLayoutEffect.md
  83. 34
      beta/src/content/reference/react/useMemo.md
  84. 6
      beta/src/content/reference/react/useReducer.md
  85. 8
      beta/src/content/reference/react/useRef.md
  86. 6
      beta/src/content/reference/react/useState.md
  87. 12
      beta/src/content/reference/react/useSyncExternalStore.md
  88. 18
      beta/src/content/reference/react/useTransition.md
  89. 6
      beta/src/hooks/useActiveSection.ts
  90. 6
      beta/src/hooks/usePathWithoutQuerystring.ts
  91. 122
      beta/src/sidebarReference.json
  92. 48
      beta/vercel.json

8
beta/src/components/Layout/Footer.tsx

@ -112,11 +112,13 @@ export function Footer() {
</FooterLink>
</div>
<div className="flex flex-col">
<FooterLink href="/apis/react" isHeader={true}>
<FooterLink href="/reference/react" isHeader={true}>
API Reference
</FooterLink>
<FooterLink href="/apis/react">React APIs</FooterLink>
<FooterLink href="/apis/react-dom">React DOM APIs</FooterLink>
<FooterLink href="/reference/react">React APIs</FooterLink>
<FooterLink href="/reference/react-dom">
React DOM APIs
</FooterLink>
</div>
<div className="flex flex-col sm:col-start-2 xl:col-start-4">
<FooterLink href="/" isHeader={true}>

18
beta/src/components/Layout/Nav/Nav.tsx

@ -20,7 +20,7 @@ import {SidebarContext} from 'components/Layout/useRouteMeta';
import {SidebarRouteTree} from '../Sidebar/SidebarRouteTree';
import type {RouteItem} from '../useRouteMeta';
import sidebarLearn from '../../../sidebarLearn.json';
import sidebarAPIs from '../../../sidebarAPIs.json';
import sidebarReference from '../../../sidebarReference.json';
declare global {
interface Window {
@ -117,8 +117,8 @@ export default function Nav() {
case 'learn':
routeTree = sidebarLearn as RouteItem;
break;
case 'apis':
routeTree = sidebarAPIs as RouteItem;
case 'reference':
routeTree = sidebarReference as RouteItem;
break;
}
}
@ -185,7 +185,7 @@ export default function Nav() {
});
}, [showFeedback]);
function selectTab(nextTab: 'learn' | 'apis') {
function selectTab(nextTab: 'learn' | 'reference') {
setTab(nextTab);
scrollParentRef.current!.scrollTop = 0;
}
@ -252,8 +252,8 @@ export default function Nav() {
isActive={section === 'learn' || section === 'home'}>
Learn
</NavLink>
<NavLink href="/apis/react" isActive={section === 'apis'}>
API
<NavLink href="/reference/react" isActive={section === 'reference'}>
Reference
</NavLink>
</div>
<div className="flex my-4 h-10 mx-0 w-full lg:hidden justify-end lg:max-w-sm">
@ -318,9 +318,9 @@ export default function Nav() {
Learn
</TabButton>
<TabButton
isActive={tab === 'apis'}
onClick={() => selectTab('apis')}>
API
isActive={tab === 'reference'}
onClick={() => selectTab('reference')}>
Reference
</TabButton>
</div>
)}

6
beta/src/components/Layout/Page.tsx

@ -12,7 +12,7 @@ import {Footer} from './Footer';
import {Toc} from './Toc';
import SocialBanner from '../SocialBanner';
import sidebarLearn from '../../sidebarLearn.json';
import sidebarAPIs from '../../sidebarAPIs.json';
import sidebarReference from '../../sidebarReference.json';
import type {TocItem} from 'components/MDX/TocContext';
interface PageProps {
@ -25,8 +25,8 @@ export function Page({children, toc}: PageProps) {
const section = useActiveSection();
let routeTree = sidebarLearn as RouteItem;
switch (section) {
case 'apis':
routeTree = sidebarAPIs as RouteItem;
case 'reference':
routeTree = sidebarReference as RouteItem;
break;
}
return (

2
beta/src/components/MDX/HomepageHero.tsx

@ -29,7 +29,7 @@ function HomepageHero() {
</YouWillLearnCard>
</div>
<div className="flex flex-col justify-center">
<YouWillLearnCard title="API Reference" path="/apis/react">
<YouWillLearnCard title="API Reference" path="/reference/react">
<p>
Look up the API of React Hooks, and see their shape with
color-coded signatures.

43
beta/src/content/apis/react-dom/index.md

@ -1,43 +0,0 @@
---
title: react-dom
---
<Intro>
The `react-dom` package contains methods that are only supported for the web applications (which run in the browser DOM environment). They are not supported for React Native.
</Intro>
---
## React DOM APIs {/*react-dom-apis*/}
These APIs can be imported from your components. They are rarely used:
* [`createPortal`](/apis/react-dom/createPortal) lets you render child components in a different part of the DOM tree.
* [`flushSync`](/apis/react-dom/flushSync) lets you force React to flush a state update and update the DOM synchronously.
---
## React DOM entry points {/*react-dom-entry-points*/}
The `react-dom` package provides two additional entry points:
* [`react-dom/client`](/apis/react-dom/client) contains APIs to render React components on the client (in the browser).
* [`react-dom/server`](/apis/react-dom/server) contains APIs to render React components on the server.
---
## Deprecated React DOM APIs {/*deprecated-react-dom-apis*/}
<Deprecated>
These APIs will be removed in a future major version of React.
</Deprecated>
* [`findDOMNode`](/apis/react-dom/findDOMNode) finds the closest DOM node corresponding to a class component instance.
* [`hydrate`](/apis/react-dom/hydrate) mounts a tree into the DOM created from server HTML. Deprecated in favor of [`hydrateRoot`](/apis/react-dom/client/hydrateRoot).
* [`render`](/apis/react-dom/render) mounts a tree into the DOM. Deprecated in favor of [`createRoot`](/apis/react-dom/client/createRoot).
* [`unmountComponentAtNode`](/apis/react-dom/unmountComponentAtNode) unmounts a tree from the DOM. Deprecated in favor of [`root.unmount()`.](/apis/react-dom/client/createRoot#root-unmount)

21
beta/src/content/apis/react/apis.md

@ -1,21 +0,0 @@
---
title: "react: APIs"
---
<Intro>
In addition to [Hooks](/apis/react) and [Components](/apis/react/components), the `react` package exports a few other APIs that are useful for defining components. This page lists all the remaining modern React APIs.
</Intro>
<InlineToc />
---
## React APIs {/*react-apis*/}
* [`createContext`](/apis/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/apis/react/useContext)
* [`forwardRef`](/apis/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/apis/react/useRef)
* [`lazy`](/apis/react/lazy) lets you defer loading a component's code until it's rendered for the first time.
* [`memo`](/apis/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/apis/react/useMemo) and [`useCallback`.](/apis/react/useCallback)
* [`startTransition`](/apis/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/apis/react/useTransition)

20
beta/src/content/apis/react/components.md

@ -1,20 +0,0 @@
---
title: "react: Components"
---
<Intro>
React exposes a few built-in components that you can use in your JSX.
</Intro>
<InlineToc />
---
## Built-in React components {/*built-in-react-components*/}
* [`<Fragment>`](/apis/react/Fragment), alternatively written as `<>...</>`, lets you group multiple JSX nodes together.
* [`<Profiler>`](/apis/react/Profiler) lets you measure rendering performance of a React tree programmatically.
* [`<Suspense>`](/apis/react/Suspense) lets you display a fallback while the child components are loading.
* [`<StrictMode>`](/apis/react/StrictMode) enables extra development-only checks that help you find bugs early.

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

@ -1,34 +0,0 @@
---
title: "react: Legacy APIs"
---
<Intro>
These APIs are exported from the `react` package, but they are not recommended for use in the newly written code. See the linked individual API pages for the suggested alternatives.
</Intro>
---
## Legacy React APIs {/*legacy-react-apis*/}
* [`Children`](/apis/react/Children) lets you manipulate and transform the JSX received as the `children` prop. [See alternatives.](/apis/react/Children#alternatives)
* [`cloneElement`](/apis/react/cloneElement) lets you create a React element using another element as a starting point. [See alternatives.](/apis/react/cloneElement#alternatives)
* [`Component`](/apis/react/Component) lets you define a React component as a JavaScript class. [See alternatives.](/apis/react/Component#alternatives)
* [`createElement`](/apis/react/createElement) lets you create a React element. Typically, you'll use JSX instead.
* [`createRef`](/apis/react/createRef) creates a ref object which can contain arbitrary value. [See alternatives.](/apis/react/createRef#alternatives)
* [`isValidElement`](/apis/react/isValidElement) checks whether a value is a React element. Typically used with [`cloneElement`.](/apis/react/cloneElement)
* [`PureComponent`](/apis/react/PureComponent) is similar to [`Component`,](/apis/react/Component) but it skip re-renders with same props. [See alternatives.](/apis/react/PureComponent#alternatives)
---
## Deprecated React APIs {/*deprecated-react-apis*/}
<Deprecated>
These APIs will be removed in a future major version of React.
</Deprecated>
* [`createFactory`](/apis/react/createFactory) lets you create a function that produces React elements of a certain type.

2
beta/src/content/learn/add-react-to-a-website.md

@ -229,7 +229,7 @@ If you're getting comfortable with build tools and want them to do more for you,
Originally JSX was introduced to make writing components with React feel as familiar as writing HTML. Since then, the syntax has become widespread. However, there may be instances where you do not want to use or cannot use JSX. You have two options:
- Use a JSX alternative like [htm](https://github.com/developit/htm) which uses JavaScript [template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) instead of a compiler.
- Use [`React.createElement()`](/apis/react/createElement) which has a special structure explained below.
- Use [`React.createElement()`](/reference/react/createElement) which has a special structure explained below.
With JSX, you would write a component like so:

2
beta/src/content/learn/adding-interactivity.md

@ -76,7 +76,7 @@ Read **[Responding to Events](/learn/responding-to-events)** to learn how to add
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state.*
You can add state to a component with a [`useState`](/apis/react/useState) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
You can add state to a component with a [`useState`](/reference/react/useState) Hook. *Hooks* are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
```js
const [index, setIndex] = useState(0);

4
beta/src/content/learn/index.md

@ -302,7 +302,7 @@ Notice how `onClick={handleClick}` has no parentheses at the end! Do not _call_
Often, you'll want your component to "remember" some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add *state* to your component.
First, import [`useState`](/apis/react/useState) from React:
First, import [`useState`](/reference/react/useState) from React:
```js
import { useState } from 'react';
@ -382,7 +382,7 @@ Notice how each button "remembers" its own `count` state and doesn't affect othe
## Using Hooks {/*using-hooks*/}
Functions starting with `use` are called *Hooks*. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [React API reference.](/apis/react) You can also write your own Hooks by combining the existing ones.
Functions starting with `use` are called *Hooks*. `useState` is a built-in Hook provided by React. You can find other built-in Hooks in the [React API reference.](/reference/react) You can also write your own Hooks by combining the existing ones.
Hooks are more restrictive than regular functions. You can only call Hooks *at the top level* of your components (or other Hooks). If you want to use `useState` in a condition or a loop, extract a new component and put it there.

4
beta/src/content/learn/keeping-components-pure.md

@ -195,7 +195,7 @@ While functional programming relies heavily on purity, at some point, somewhere,
In React, **side effects usually belong inside [event handlers.](/learn/responding-to-events)** Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined *inside* your component, they don't run *during* rendering! **So event handlers don't need to be pure.**
If you've exhausted all other options and can't find the right event handler for your side effect, you can still attach it to your returned JSX with a [`useEffect`](/apis/react/useEffect) call in your component. This tells React to execute it later, after rendering, when side effects are allowed. **However, this approach should be your last resort.**
If you've exhausted all other options and can't find the right event handler for your side effect, you can still attach it to your returned JSX with a [`useEffect`](/reference/react/useEffect) call in your component. This tells React to execute it later, after rendering, when side effects are allowed. **However, this approach should be your last resort.**
When possible, try to express your logic with rendering alone. You'll be surprised how far this can take you!
@ -206,7 +206,7 @@ When possible, try to express your logic with rendering alone. You'll be surpris
Writing pure functions takes some habit and discipline. But it also unlocks marvelous opportunities:
* Your components could run in a different environment—for example, on the server! Since they return the same result for the same inputs, one component can serve many user requests.
* You can improve performance by [skipping rendering](/apis/react/memo) components whose inputs have not changed. This is safe because pure functions always return the same results, so they are safe to cache.
* You can improve performance by [skipping rendering](/reference/react/memo) components whose inputs have not changed. This is safe because pure functions always return the same results, so they are safe to cache.
* If some data changes in the middle of rendering a deep component tree, React can restart rendering without wasting time to finish the outdated render. Purity makes it safe to stop calculating at any time.
Every new React feature we're building takes advantage of purity. From data fetching to animations to performance, keeping components pure unlocks the power of the React paradigm.

4
beta/src/content/learn/lifecycle-of-reactive-effects.md

@ -581,7 +581,7 @@ Mutable values (including global variables) aren't reactive.
**A mutable value like [`location.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/Location/pathname) can't be a dependency.** It's mutable, so it can change at any time completely outside of the React rendering data flow. Changing it wouldn't trigger a re-render of your component. Therefore, even if you specified it in the dependencies, React *wouldn't know* to re-synchronize the Effect when it changes. This also breaks the rules of React because reading mutable data during rendering (which is when you calculate the dependencies) breaks [purity of rendering.](/learn/keeping-components-pure) Instead, you should read and subscribe to an external mutable value with [`useSyncExternalStore`.](/learn/you-might-not-need-an-effect#subscribing-to-an-external-store)
**A mutable value like [`ref.current`](/apis/react/useRef#reference) or things you read from it also can't be a dependency.** The ref object returned by `useRef` itself can be a dependency, but its `current` property is intentionally mutable. It lets you [keep track of something without triggering a re-render.](/learn/referencing-values-with-refs) But since changing it doesn't trigger a re-render, it's not a reactive value, and React won't know to re-run your Effect when it changes.
**A mutable value like [`ref.current`](/reference/react/useRef#reference) or things you read from it also can't be a dependency.** The ref object returned by `useRef` itself can be a dependency, but its `current` property is intentionally mutable. It lets you [keep track of something without triggering a re-render.](/learn/referencing-values-with-refs) But since changing it doesn't trigger a re-render, it's not a reactive value, and React won't know to re-run your Effect when it changes.
As you'll learn below on this page, a linter will check for these issues automatically.
@ -685,7 +685,7 @@ Try this fix in the sandbox above. Verify that the linter error is gone, and tha
<Note>
In some cases, React *knows* that a value never changes even though it's declared inside the component. For example, the [`set` function](/apis/react/useState#setstate) returned from `useState` and the ref object returned by [`useRef`](/apis/react/useRef) are *stable*--they are guaranteed to not change on a re-render. Stable values aren't reactive, so the linter lets you omit them from the list. However, including them is allowed: they won't change, so it doesn't matter.
In some cases, React *knows* that a value never changes even though it's declared inside the component. For example, the [`set` function](/reference/react/useState#setstate) returned from `useState` and the ref object returned by [`useRef`](/reference/react/useRef) are *stable*--they are guaranteed to not change on a re-render. Stable values aren't reactive, so the linter lets you omit them from the list. However, including them is allowed: they won't change, so it doesn't matter.
</Note>

4
beta/src/content/learn/manipulating-the-dom-with-refs.md

@ -211,7 +211,7 @@ This is because **Hooks must only be called at the top-level of your component.*
One possible way around this is to get a single ref to their parent element, and then use DOM manipulation methods like [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) to "find" the individual child nodes from it. However, this is brittle and can break if your DOM structure changes.
Another solution is to **pass a function to the `ref` attribute.** This is called a [`ref` callback.](/apis/react-dom/components/common#ref-callback) React will call your ref callback with the DOM node when it's time to set the ref, and with `null` when it's time to clear it. This lets you maintain your own array or a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), and access any ref by its index or some kind of ID.
Another solution is to **pass a function to the `ref` attribute.** This is called a [`ref` callback.](/reference/react-dom/components/common#ref-callback) React will call your ref callback with the DOM node when it's time to set the ref, and with `null` when it's time to clear it. This lets you maintain your own array or a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), and access any ref by its index or some kind of ID.
This example shows how you can use this approach to scroll to an arbitrary node in a long list:
@ -318,7 +318,7 @@ li {
</Sandpack>
In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) from item ID to a DOM node. ([Refs can hold any values!](/learn/referencing-values-with-refs)) The [`ref` callback](/apis/react-dom/components/common#ref-callback) on every list item takes care to update the Map:
In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) from item ID to a DOM node. ([Refs can hold any values!](/learn/referencing-values-with-refs)) The [`ref` callback](/reference/react-dom/components/common#ref-callback) on every list item takes care to update the Map:
```js
<li

2
beta/src/content/learn/reacting-to-input-with-state.md

@ -346,7 +346,7 @@ Form states
### Step 3: Represent the state in memory with `useState` {/*step-3-represent-the-state-in-memory-with-usestate*/}
Next you'll need to represent the visual states of your component in memory with [`useState`.](/apis/react/useState) Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible.** More complexity leads to more bugs!
Next you'll need to represent the visual states of your component in memory with [`useState`.](/reference/react/useState) Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible.** More complexity leads to more bugs!
Start with the state that *absolutely must* be there. For example, you'll need to store the `answer` for the input, and the `error` (if it exists) to store the last error:

4
beta/src/content/learn/removing-effect-dependencies.md

@ -587,7 +587,7 @@ And making `messages` a dependency introduces a problem.
Every time you receive a message, `setMessages()` causes the component to re-render with a new `messages` array that includes the received message. However, since this Effect now depends on `messages`, this will *also* re-synchronize the Effect. So every new message will make the chat re-connect. The user would not like that!
To fix the issue, don't read `messages` inside the Effect. Instead, pass an [updater function](/apis/react/useState#updating-state-based-on-the-previous-state) to `setMessages`:
To fix the issue, don't read `messages` inside the Effect. Instead, pass an [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) to `setMessages`:
```js {7,10}
function ChatRoom({ roomId }) {
@ -1209,7 +1209,7 @@ export default function Timer() {
You want to update the `count` state to be `count + 1` from inside the Effect. However, this makes your Effect depend on `count`, which changes with every tick, and that's why your interval gets re-created on every tick.
To solve this, use the [updater function](/apis/react/useState#updating-state-based-on-the-previous-state) and write `setCount(c => c + 1)` instead of `setCount(count + 1)`:
To solve this, use the [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) and write `setCount(c => c + 1)` instead of `setCount(count + 1)`:
<Sandpack>

2
beta/src/content/learn/render-and-commit.md

@ -67,7 +67,7 @@ Try commenting out the `root.render()` call and see the component disappear!
### Re-renders when state updates {/*re-renders-when-state-updates*/}
Once the component has been initially rendered, you can trigger further renders by updating its state with the [`set` function.](/apis/react/useState#setstate) Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.)
Once the component has been initially rendered, you can trigger further renders by updating its state with the [`set` function.](/reference/react/useState#setstate) Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.)
<IllustrationBlock sequential>
<Illustration caption="State update..." alt="React as a server in a restaurant, serving a Card UI to the user, represented as a patron with a cursor for their head. They patron expresses they want a pink card, not a black one!" src="/images/docs/illustrations/i_rerender1.png" />

2
beta/src/content/learn/rendering-lists.md

@ -378,7 +378,7 @@ img { width: 100px; height: 100px; border-radius: 50%; }
What do you do when each item needs to render not one, but several DOM nodes?
The short [`<>...</>` Fragment](/apis/react/Fragment) syntax won't let you pass a key, so you need to either group them into a single `<div>`, or use the slightly longer and [more explicit `<Fragment>` syntax:](/apis/react/Fragment#rendering-a-list-of-fragments)
The short [`<>...</>` Fragment](/reference/react/Fragment) syntax won't let you pass a key, so you need to either group them into a single `<div>`, or use the slightly longer and [more explicit `<Fragment>` syntax:](/reference/react/Fragment#rendering-a-list-of-fragments)
```js
import { Fragment } from 'react';

8
beta/src/content/learn/reusing-logic-with-custom-hooks.md

@ -104,7 +104,7 @@ These two components work fine, but the duplication in logic between them is unf
### Extracting your own custom Hook from a component {/*extracting-your-own-custom-hook-from-a-component*/}
Imagine for a moment that, similar to [`useState`](/apis/react/useState) and [`useEffect`](/apis/react/useEffect), there was a built-in `useOnlineStatus` Hook. Then both of these components could be simplified and you could remove the duplication between them:
Imagine for a moment that, similar to [`useState`](/reference/react/useState) and [`useEffect`](/reference/react/useEffect), there was a built-in `useOnlineStatus` Hook. Then both of these components could be simplified and you could remove the duplication between them:
```js {2,7}
function StatusBar() {
@ -224,7 +224,7 @@ React applications are built from components. Components are built from Hooks, w
You must follow these naming conventions:
1. **React component names must start with a capital letter,** like `StatusBar` and `SaveButton`. React components also need to return something that React knows how to display, like a piece of JSX.
2. **Hook names must start with `use` followed by a capital letter,** like [`useState`](/apis/react/useState) (built-in) or `useOnlineStatus` (custom, like earlier on the page). Hooks may return arbitrary values.
2. **Hook names must start with `use` followed by a capital letter,** like [`useState`](/reference/react/useState) (built-in) or `useOnlineStatus` (custom, like earlier on the page). Hooks may return arbitrary values.
This convention guarantees that you can always look at a component and know where its state, Effects, and other React features might "hide". For example, if you see a `getColor()` function call inside your component, you can be sure that it can't possibly contain React state inside because its name doesn't start with `use`. However, a function call like `useOnlineStatus()` will most likely contain calls to other Hooks inside!
@ -1331,9 +1331,9 @@ export function useOnlineStatus() {
</Sandpack>
In the above example, `useOnlineStatus` is implemented with a pair of [`useState`](/apis/react/useState) and [`useEffect`.](/apis/react/useEffect) However, this isn't the best possible solution. There is a number of edge cases it doesn't consider. For example, it assumes that when the component mounts, `isOnline` is already `true`, but this may be wrong if the network already went offline. You can use the browser [`navigator.onLine`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) API to check for that, but using it directly would break if you run your React app on the server to generate the initial HTML. In short, this code could be improved.
In the above example, `useOnlineStatus` is implemented with a pair of [`useState`](/reference/react/useState) and [`useEffect`.](/reference/react/useEffect) However, this isn't the best possible solution. There is a number of edge cases it doesn't consider. For example, it assumes that when the component mounts, `isOnline` is already `true`, but this may be wrong if the network already went offline. You can use the browser [`navigator.onLine`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) API to check for that, but using it directly would break if you run your React app on the server to generate the initial HTML. In short, this code could be improved.
Luckily, React 18 includes a dedicated API called [`useSyncExternalStore`](/apis/react/useSyncExternalStore) which takes care of all of these problems for you. Here is how your `useOnlineStatus` Hook, rewritten to take advantage of this new API:
Luckily, React 18 includes a dedicated API called [`useSyncExternalStore`](/reference/react/useSyncExternalStore) which takes care of all of these problems for you. Here is how your `useOnlineStatus` Hook, rewritten to take advantage of this new API:
<Sandpack>

2
beta/src/content/learn/separating-events-from-effects.md

@ -406,7 +406,7 @@ This section describes an **experimental API that has not yet been added to Reac
</Wip>
Use a special Hook called [`useEffectEvent`](/apis/react/useEffectEvent) to extract this non-reactive logic out of your Effect:
Use a special Hook called [`useEffectEvent`](/reference/react/useEffectEvent) to extract this non-reactive logic out of your Effect:
```js {1,4-6}
import { useEffect, useEffectEvent } from 'react';

6
beta/src/content/learn/state-a-components-memory.md

@ -10,7 +10,7 @@ Components often need to change what's on the screen as a result of an interacti
<YouWillLearn>
* How to add a state variable with the [`useState`](/apis/react/useState) Hook
* How to add a state variable with the [`useState`](/reference/react/useState) Hook
* What pair of values the `useState` Hook returns
* How to add more than one state variable
* Why state is called local
@ -161,7 +161,7 @@ To update a component with new data, two things need to happen:
1. **Retain** the data between renders.
2. **Trigger** React to render the component with new data (re-rendering).
The [`useState`](/apis/react/useState) Hook provides those two things:
The [`useState`](/reference/react/useState) Hook provides those two things:
1. A **state variable** to retain the data between renders.
2. A **state setter function** to update the variable and trigger React to render the component again.
@ -347,7 +347,7 @@ State is just one of those features, but you will meet the other Hooks later.
### Anatomy of `useState` {/*anatomy-of-usestate*/}
When you call [`useState`](/apis/react/useState), you are telling React that you want this component to remember something:
When you call [`useState`](/reference/react/useState), you are telling React that you want this component to remember something:
```js
const [index, setIndex] = useState(0);

16
beta/src/content/learn/synchronizing-with-effects.md

@ -53,7 +53,7 @@ Let's look at each of these steps in detail.
### Step 1: Declare an Effect {/*step-1-declare-an-effect*/}
To declare an Effect in your component, import the [`useEffect` Hook](/apis/react/useEffect) from React:
To declare an Effect in your component, import the [`useEffect` Hook](/reference/react/useEffect) from React:
```js
import { useEffect } from 'react';
@ -397,7 +397,7 @@ video { width: 250px; }
</Sandpack>
The dependency array can contain multiple dependencies. React will only skip re-running the Effect if *all* of the dependencies you specify have exactly the same values as they had during the previous render. React compares the dependency values using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. See the [`useEffect` API reference](/apis/react/useEffect#reference) for more details.
The dependency array can contain multiple dependencies. React will only skip re-running the Effect if *all* of the dependencies you specify have exactly the same values as they had during the previous render. React compares the dependency values using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. See the [`useEffect` API reference](/reference/react/useEffect#reference) for more details.
**Notice that you can't "choose" your dependencies.** You will get a lint error if the dependencies you specified don't match what React expects based on the code inside your Effect. This helps catch many bugs in your code. If your Effect uses some value but you *don't* want to re-run the Effect when it changes, you'll need to [*edit the Effect code itself* to not "need" that dependency.](/learn/lifecycle-of-reactive-effects#what-to-do-when-you-dont-want-to-re-synchronize)
@ -441,7 +441,7 @@ function VideoPlayer({ src, isPlaying }) {
}, [isPlaying]);
```
This is because the `ref` object has a *stable identity:* React guarantees [you'll always get the same object](/apis/react/useRef#returns) from the same `useRef` call on every render. It never changes, so it will never by itself cause the Effect to re-run. Therefore, it does not matter whether you include it or not. Including it is fine too:
This is because the `ref` object has a *stable identity:* React guarantees [you'll always get the same object](/reference/react/useRef#returns) from the same `useRef` call on every render. It never changes, so it will never by itself cause the Effect to re-run. Therefore, it does not matter whether you include it or not. Including it is fine too:
```js {9}
function VideoPlayer({ src, isPlaying }) {
@ -455,7 +455,7 @@ function VideoPlayer({ src, isPlaying }) {
}, [isPlaying, ref]);
```
The [`set` functions](/apis/react/useState#setstate) returned by `useState` also have stable identity, so you will often see them omitted from the dependencies too. If the linter lets you omit a dependency without errors, it is safe to do.
The [`set` functions](/reference/react/useState#setstate) returned by `useState` also have stable identity, so you will often see them omitted from the dependencies too. If the linter lets you omit a dependency without errors, it is safe to do.
Omitting always-stable dependencies only works when the linter can "see" that the object is stable. For example, if `ref` was passed from a parent component, you would have to specify it in the dependency array. However, this is good because you can't know whether the parent component always passes the same ref, or passes one of several refs conditionally. So your Effect _would_ depend on which ref is passed.
@ -586,7 +586,7 @@ Now you get three console logs in development:
**This is the correct behavior in development.** By remounting your component, React verifies that navigating away and back would not break your code. Disconnecting and then connecting again is exactly what should happen! When you implement the cleanup well, there should be no user-visible difference between running the Effect once vs running it, cleaning it up, and running it again. There's an extra connect/disconnect call pair because React is probing your code for bugs in development. This is normal and you shouldn't try to make it go away.
**In production, you would only see `"✅ Connecting..."` printed once.** Remounting components only happens in development to help you find Effects that need cleanup. You can turn off [Strict Mode](/apis/react/StrictMode) to opt out of the development behavior, but we recommend keeping it on. This lets you find many bugs like the one above.
**In production, you would only see `"✅ Connecting..."` printed once.** Remounting components only happens in development to help you find Effects that need cleanup. You can turn off [Strict Mode](/reference/react/StrictMode) to opt out of the development behavior, but we recommend keeping it on. This lets you find many bugs like the one above.
## How to handle the Effect firing twice in development? {/*how-to-handle-the-effect-firing-twice-in-development*/}
@ -724,7 +724,7 @@ In development, `logVisit` will be called twice for every URL, so you might be t
**In production, there will be no duplicate visit logs.**
To debug the analytics events you're sending, you can deploy your app to a staging environment (which runs in production mode) or temporarily opt out of [Strict Mode](/apis/react/StrictMode) and its development-only remounting checks. You may also send analytics from the route change event handlers instead of Effects. For even more precise analytics, [intersection observers](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) can help track which components are in the viewport and how long they remain visible.
To debug the analytics events you're sending, you can deploy your app to a staging environment (which runs in production mode) or temporarily opt out of [Strict Mode](/reference/react/StrictMode) and its development-only remounting checks. You may also send analytics from the route change event handlers instead of Effects. For even more precise analytics, [intersection observers](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) can help track which components are in the viewport and how long they remain visible.
### Not an Effect: Initializing the application {/*not-an-effect-initializing-the-application*/}
@ -941,7 +941,7 @@ Finally, let's say the user navigates away, and the `ChatRoom` component unmount
#### Development-only behaviors {/*development-only-behaviors*/}
When [Strict Mode](/apis/react/StrictMode) is on, React remounts every component once after mount (state and DOM are preserved). This [helps you find Effects that need cleanup](#step-3-add-cleanup-if-needed) and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
When [Strict Mode](/reference/react/StrictMode) is on, React remounts every component once after mount (state and DOM are preserved). This [helps you find Effects that need cleanup](#step-3-add-cleanup-if-needed) and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
</DeepDive>
@ -1371,7 +1371,7 @@ body {
<Solution>
When [Strict Mode](/apis/react/StrictMode) is on (like in the sandboxes on this site), React remounts each component once in development. This causes the interval to be set up twice, and this is why each second the counter increments twice.
When [Strict Mode](/reference/react/StrictMode) is on (like in the sandboxes on this site), React remounts each component once in development. This causes the interval to be set up twice, and this is why each second the counter increments twice.
However, React's behavior is not the *cause* of the bug: the bug already exists in the code. React's behavior makes the bug more noticeable. The real cause is that this Effect starts a process but doesn't provide a way to clean it up.

2
beta/src/content/learn/thinking-in-react.md

@ -273,7 +273,7 @@ Now let's run through our strategy for this state:
So the state values will live in `FilterableProductTable`.
Add state to the component with the [`useState()` Hook.](/apis/react/useState) Hooks let you "hook into" a component's [render cycle.](/learn/render-and-commit) Add two state variables at the top of `FilterableProductTable` and specify the initial state of your application:
Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks let you "hook into" a component's [render cycle.](/learn/render-and-commit) Add two state variables at the top of `FilterableProductTable` and specify the initial state of your application:
```js
function FilterableProductTable({ products }) {

2
beta/src/content/learn/tutorial-tic-tac-toe.md

@ -1361,7 +1361,7 @@ The end result is the same but by not mutating (changing the underlying data) di
Immutability makes complex features much easier to implement. Later in this tutorial, you will implement a "time travel" feature that lets you review the game's history and "jump back" to past moves. This functionality isn't specific to games--an ability to undo and redo certain actions is a common requirement for apps. Avoiding direct data mutation lets you keep previous versions of the data intact, and reuse them (or reset to them) later.
There is also another benefit of immutability. By default, all child components re-render automatically when the state of a parent component changes. This includes even the child components that weren't affected by the change. Although re-rendering is not by itself noticeable to the user (you shouldn't actively try to avoid it!), you might want to skip re-rendering a part of the tree that clearly wasn't affected by it for performance reasons. Immutability makes it very cheap for components to compare whether their data has changed or not. You can learn more about how React chooses when to re-render a component in [the `memo` API reference](/apis/react/memo) documentation.
There is also another benefit of immutability. By default, all child components re-render automatically when the state of a parent component changes. This includes even the child components that weren't affected by the change. Although re-rendering is not by itself noticeable to the user (you shouldn't actively try to avoid it!), you might want to skip re-rendering a part of the tree that clearly wasn't affected by it for performance reasons. Immutability makes it very cheap for components to compare whether their data has changed or not. You can learn more about how React chooses when to re-render a component in [the `memo` API reference](/reference/react/memo) documentation.
### Taking turns {/*taking-turns*/}

2
beta/src/content/learn/updating-objects-in-state.md

@ -798,7 +798,7 @@ Notice how much more concise the event handlers have become. You can mix and mat
There are a few reasons:
* **Debugging:** If you use `console.log` and don't mutate state, your past logs won't get clobbered by the more recent state changes. So you can clearly see how state has changed between renders.
* **Optimizations:** Common React [optimization strategies](/apis/react/memo) rely on skipping work if previous props or state are the same as the next ones. If you never mutate state, it is very fast to check whether there were any changes. If `prevObj === obj`, you can be sure that nothing could have changed inside of it.
* **Optimizations:** Common React [optimization strategies](/reference/react/memo) rely on skipping work if previous props or state are the same as the next ones. If you never mutate state, it is very fast to check whether there were any changes. If `prevObj === obj`, you can be sure that nothing could have changed inside of it.
* **New Features:** The new React features we're building rely on state being [treated like a snapshot.](/learn/state-as-a-snapshot) If you're mutating past versions of state, that may prevent you from using the new features.
* **Requirement Changes:** Some application features, like implementing Undo/Redo, showing a history of changes, or letting the user reset a form to earlier values, are easier to do when nothing is mutated. This is because you can keep past copies of state in memory, and reuse them when appropriate. If you start with a mutative approach, features like this can be difficult to add later on.
* **Simpler Implementation:** Because React does not rely on mutation, it does not need to do anything special with your objects. It does not need to hijack their properties, always wrap them into Proxies, or do other work at initialization as many "reactive" solutions do. This is also why React lets you put any object into state--no matter how large--without additional performance or correctness pitfalls.

2
beta/src/content/learn/writing-markup-with-jsx.md

@ -169,7 +169,7 @@ If you don't want to add an extra `<div>` to your markup, you can write `<>` and
</>
```
This empty tag is called a *[Fragment.](/apis/react/Fragment)* Fragments let you group things without leaving any trace in the browser HTML tree.
This empty tag is called a *[Fragment.](/reference/react/Fragment)* Fragments let you group things without leaving any trace in the browser HTML tree.
<DeepDive>

12
beta/src/content/learn/you-might-not-need-an-effect.md

@ -93,7 +93,7 @@ function TodoList({ todos, filter }) {
In many cases, this code is fine! But maybe `getFilteredTodos()` is slow or you have a lot of `todos`. In that case you don't want to recalculate `getFilteredTodos()` if some unrelated state variable like `newTodo` has changed.
You can cache (or ["memoize"](https://en.wikipedia.org/wiki/Memoization)) an expensive calculation by wrapping it in a [`useMemo`](/apis/react/useMemo) Hook:
You can cache (or ["memoize"](https://en.wikipedia.org/wiki/Memoization)) an expensive calculation by wrapping it in a [`useMemo`](/reference/react/useMemo) Hook:
```js {5-8}
import { useMemo, useState } from 'react';
@ -123,7 +123,7 @@ function TodoList({ todos, filter }) {
**This tells React that you don't want the inner function to re-run unless either `todos` or `filter` have changed.** React will remember the return value of `getFilteredTodos()` during the initial render. During the next renders, it will check if `todos` or `filter` are different. If they're the same as last time, `useMemo` will return the last result it has stored. But if they are different, React will call the wrapped function again (and store _that_ result instead).
The function you wrap in [`useMemo`](/apis/react/useMemo) runs during rendering, so this only works for [pure calculations.](/learn/keeping-components-pure)
The function you wrap in [`useMemo`](/reference/react/useMemo) runs during rendering, so this only works for [pure calculations.](/learn/keeping-components-pure)
<DeepDive>
@ -151,7 +151,7 @@ console.timeEnd('filter array');
Keep in mind that your machine is probably faster than your users' so it's a good idea to test the performance with an artificial slowdown. For example, Chrome offers a [CPU Throttling](https://developer.chrome.com/blog/new-in-devtools-61/#throttling) option for this.
Also note that measuring performance in development will not give you the most accurate results. (For example, when [Strict Mode](/apis/react/StrictMode) is on, you will see each component render twice rather than once.) To get the most accurate timings, build your app for production and test it on a device like your users have.
Also note that measuring performance in development will not give you the most accurate results. (For example, when [Strict Mode](/reference/react/StrictMode) is on, you will see each component render twice rather than once.) To get the most accurate timings, build your app for production and test it on a device like your users have.
</DeepDive>
@ -234,7 +234,7 @@ function List({ items }) {
}
```
[Storing information from previous renders](/apis/react/useState#storing-information-from-previous-renders) like this can be hard to understand, but it’s better than updating the same state in an Effect. In the above example, `setSelection` is called directly during a render. React will re-render the `List` *immediately* after it exits with a `return` statement. By that point, React hasn't rendered the `List` children or updated the DOM yet, so this lets the `List` children skip rendering the stale `selection` value.
[Storing information from previous renders](/reference/react/useState#storing-information-from-previous-renders) like this can be hard to understand, but it’s better than updating the same state in an Effect. In the above example, `setSelection` is called directly during a render. React will re-render the `List` *immediately* after it exits with a `return` statement. By that point, React hasn't rendered the `List` children or updated the DOM yet, so this lets the `List` children skip rendering the stale `selection` value.
When you update a component during rendering, React throws away the returned JSX and immediately retries rendering. To avoid very slow cascading retries, React only lets you update the *same* component's state during a render. If you update another component's state during a render, you'll see an error. A condition like `items !== prevItems` is necessary to avoid loops. You may adjust state like this, but any other side effects (like changing the DOM or setting a timeout) should remain in event handlers or Effects to [keep your components predictable.](/learn/keeping-components-pure)
@ -658,7 +658,7 @@ function ChatIndicator() {
Here, the component subscribes to an external data store (in this case, the browser `navigator.onLine` API). Since this API does not exist on the server (so it can't be used to generate the initial HTML), initially the state is set to `true`. Whenever the value of that data store changes in the browser, the component updates its state.
Although it's common to use Effects for this, React has a purpose-built Hook for subscribing to an external store that is preferred instead. Delete the Effect and replace it with a call to [`useSyncExternalStore`](/apis/react/useSyncExternalStore):
Although it's common to use Effects for this, React has a purpose-built Hook for subscribing to an external store that is preferred instead. Delete the Effect and replace it with a call to [`useSyncExternalStore`](/reference/react/useSyncExternalStore):
```js {11-16}
function subscribe(callback) {
@ -685,7 +685,7 @@ function ChatIndicator() {
}
```
This approach is less error-prone than manually syncing mutable data to React state with an Effect. Typically, you'll write a custom Hook like `useOnlineStatus()` above so that you don't need to repeat this code in the individual components. [Read more about subscribing to external stores from React components.](/apis/react/useSyncExternalStore)
This approach is less error-prone than manually syncing mutable data to React state with an Effect. Typically, you'll write a custom Hook like `useOnlineStatus()` above so that you don't need to repeat this code in the individual components. [Read more about subscribing to external stores from React components.](/reference/react/useSyncExternalStore)
### Fetching data {/*fetching-data*/}

22
beta/src/content/apis/react-dom/client/createRoot.md → beta/src/content/reference/react-dom/client/createRoot.md

@ -44,16 +44,16 @@ An app fully built with React will usually only have one `createRoot` call for i
* **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.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/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.
* If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](/reference/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`.
* 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`](/reference/react-dom/createPortal) instead of `createRoot`.
---
@ -71,7 +71,7 @@ React will display `<App />` in the `root`, and take over managing the DOM insid
#### 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`.
* `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()`](/reference/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
@ -82,9 +82,9 @@ React will display `<App />` in the `root`, and take over managing the DOM insid
* 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 your root's DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](/reference/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.
* 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](/reference/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.
---
@ -186,7 +186,7 @@ function Counter() {
**If your app is fully built with React, you shouldn't need to create any more roots, or to call [`root.render`](#root-render) again.**
From this point on, React will manage the DOM of your entire app. To add more components, [nest them inside the `App` component.](/learn/importing-and-exporting-components) When you need to update the UI, each of your components can do this by [using state.](/apis/react/useState) When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](/apis/react-dom/createPortal)
From this point on, React will manage the DOM of your entire app. To add more components, [nest them inside the `App` component.](/learn/importing-and-exporting-components) When you need to update the UI, each of your components can do this by [using state.](/reference/react/useState) When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](/reference/react-dom/createPortal)
<Note>
@ -196,13 +196,13 @@ When your HTML is empty, the user sees a blank page until the app's JavaScript c
<div id="root"></div>
```
This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](/apis/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend to [use a framework](/learn/start-a-new-react-project#building-with-a-full-featured-framework) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).*
This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](/reference/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend to [use a framework](/learn/start-a-new-react-project#building-with-a-full-featured-framework) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).*
</Note>
<Pitfall>
**Apps using server rendering or static generation must call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.
**Apps using server rendering or static generation must call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them.
</Pitfall>
@ -332,7 +332,7 @@ 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.
It is uncommon to call `render` multiple times. Usually, you'll [update state](/reference/react/useState) inside one of the components instead.
---
## Troubleshooting {/*troubleshooting*/}
@ -409,7 +409,7 @@ If you can't get it working, check out [Adding React to a Website](/learn/add-re
If your app is server-rendered and includes the initial HTML generated by React, you might notice that creating a root and calling `root.render` deletes all that HTML, and then re-creates all the DOM nodes from scratch. This can be slower, resets focus and scroll positions, and may lose other user input.
Server-rendered apps must use [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) instead of `createRoot`:
Server-rendered apps must use [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) instead of `createRoot`:
```js {1,4-7}
import { hydrateRoot } from 'react-dom/client';

18
beta/src/content/apis/react-dom/client/hydrateRoot.md → beta/src/content/reference/react-dom/client/hydrateRoot.md

@ -4,7 +4,7 @@ title: hydrateRoot
<Intro>
`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/apis/react-dom/server)
`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server)
```js
const root = hydrateRoot(domNode, reactNode, options?)
@ -40,7 +40,7 @@ React will attach to the HTML that exists inside the `domNode`, and take over ma
* **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** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/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*/}
@ -52,7 +52,7 @@ React will attach to the HTML that exists inside the `domNode`, and take over ma
* `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.
* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/reference/react-dom/client/createRoot) instead.
---
@ -70,7 +70,7 @@ React will update `<App />` in the hydrated `root`.
#### 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`.
* `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()`](/reference/react/createElement), a string, a number, `null`, or `undefined`.
#### Returns {/*root-render-returns*/}
@ -119,7 +119,7 @@ Calling `root.unmount` will unmount all the components in the root and "detach"
### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
If your app's HTML was generated by [`react-dom/server`](/apis/react-dom/client/createRoot), you need to *hydrate* it on the client.
If your app's HTML was generated by [`react-dom/server`](/reference/react-dom/client/createRoot), you need to *hydrate* it on the client.
```js [[1, 3, "document.getElementById('root')"], [2, 3, "<App />"]]
import { hydrateRoot } from 'react-dom/client';
@ -176,7 +176,7 @@ function Counter() {
</Sandpack>
You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/reference/react/useState)
<Pitfall>
@ -272,7 +272,7 @@ This only works one level deep, and is intended to be an escape hatch. Don’t o
### Handling different client and server content {/*handling-different-client-and-server-content*/}
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/apis/react/useState) like `isClient`, which you can set to `true` in an [Effect](/apis/react/useEffect):
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](/reference/react/useEffect):
<Sandpack>
@ -324,7 +324,7 @@ This approach makes hydration slower because your components have to render twic
### Updating a hydrated root component {/*updating-a-hydrated-root-component*/}
After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/apis/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.**
After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.**
If you call `root.render` at some point after hydration, and the component tree structure matches up with what was previously rendered, React will [preserve the state.](/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive:
@ -368,4 +368,4 @@ 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.
It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead.

4
beta/src/content/apis/react-dom/client/index.md → beta/src/content/reference/react-dom/client/index.md

@ -12,8 +12,8 @@ The `react-dom/client` APIs let you render React components on the client (in th
## React DOM Client APIs {/*react-dom-client-apis*/}
* [`createRoot`](/apis/react-dom/client/createRoot) lets you create a root to display React components inside a browser DOM node.
* [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/apis/react-dom/server)
* [`createRoot`](/reference/react-dom/client/createRoot) lets you create a root to display React components inside a browser DOM node.
* [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server)
---

18
beta/src/content/apis/react-dom/components/common.md → beta/src/content/reference/react-dom/components/common.md

@ -20,15 +20,15 @@ All built-in browser components, such as [`<div>`](https://developer.mozilla.org
These special React props are supported for all built-in components:
* `children`: A React node (an element, a string, a number, [a portal,](/apis/react-dom/createPortal) an empty node like `null`, `undefined` and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the `children` prop implicitly by nesting tags like `<div><span /></div>`.
* `children`: A React node (an element, a string, a number, [a portal,](/reference/react-dom/createPortal) an empty node like `null`, `undefined` and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the `children` prop implicitly by nesting tags like `<div><span /></div>`.
* `dangerouslySetInnerHTML`: An object of the form `{ __html: '<p>some html</p>' }` with a raw HTML string inside. Overrides the [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn't trusted (for example, if it's based on user data), you risk introducing an [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerability. [Read more about using `dangerouslySetInnerHTML`.](#dangerously-setting-the-inner-html)
* `ref`: A ref object from [`useRef`](/apis/react/useRef) or [`createRef`](/apis/react/createRef), or a [`ref` callback function,](#ref-callback) or a string for [legacy refs.](https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs) Your ref will be filled with the DOM element for this node. [Read more about manipulating the DOM with refs.](#manipulating-a-dom-node-with-a-ref)
* `ref`: A ref object from [`useRef`](/reference/react/useRef) or [`createRef`](/reference/react/createRef), or a [`ref` callback function,](#ref-callback) or a string for [legacy refs.](https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs) Your ref will be filled with the DOM element for this node. [Read more about manipulating the DOM with refs.](#manipulating-a-dom-node-with-a-ref)
* `suppressContentEditableWarning`: A boolean. If `true`, suppresses the warning that React shows for elements that both have `children` and `contentEditable={true}` (which normally do not work together). Use this if you're building a text input library that manages the `contentEditable` content manually.
* `suppressHydrationWarning`: A boolean. If you use [server rendering,](/apis/react-dom/server) normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set `suppressHydrationWarning` to `true`, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don't overuse it. [Read more about suppressing hydration errors.](/apis/react-dom/client/hydrateRoot#suppressing-unavoidable-hydration-mismatch-errors)
* `suppressHydrationWarning`: A boolean. If you use [server rendering,](/reference/react-dom/server) normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set `suppressHydrationWarning` to `true`, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don't overuse it. [Read more about suppressing hydration errors.](/reference/react-dom/client/hydrateRoot#suppressing-unavoidable-hydration-mismatch-errors)
* `style`: An object with CSS styles, for example `{ fontWeight: 'bold', margin: 20 }`. Similarly to the DOM [`style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) property, the CSS property names need to be written as `camelCase`, for example `fontWeight` instead of `font-weight`. You can pass strings or numbers as values. If you pass a number, like `width: 100`, React will automatically append `px` ("pixels") to the value unless it's a [unitless property.](https://github.com/facebook/react/blob/81d4ee9ca5c405dce62f64e61506b8e155f38d8d/packages/react-dom-bindings/src/shared/CSSProperty.js#L8-L57) We recommend using `style` only for dynamic styles where you don't know the style values ahead of time. In other cases, applying plain CSS classes with `className` is more efficient. [Read more about applying CSS with `className` and `styles`.](#applying-css-styles)
@ -43,10 +43,10 @@ These standard DOM props are also supported for all built-in components:
* [`dir`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir): Either `'ltr'` or `'rtl'`. Specifies the text direction of the element.
* [`draggable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable): A boolean. Specifies whether the element is draggable. Part of [HTML Drag and Drop API.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)
* [`enterKeyHint`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/enterKeyHint): A string. Specifies which action to present for the enter key on virtual keyboards.
* [`htmlFor`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor): A string. For [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) and [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output), lets you [associate the label with some control.](/apis/react-dom/components/input#providing-a-label-for-an-input) Same as [`for` HTML attribute.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/for) React uses the standard DOM property names (`htmlFor`) instead of HTML attribute names.
* [`htmlFor`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor): A string. For [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) and [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output), lets you [associate the label with some control.](/reference/react-dom/components/input#providing-a-label-for-an-input) Same as [`for` HTML attribute.](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/for) React uses the standard DOM property names (`htmlFor`) instead of HTML attribute names.
* [`hidden`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden): A boolean or a string. Specifies whether the element should be hidden.
* [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id): A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it with [`useId`](/apis/react/useId) to avoid clashes between multiple instances of the same component.
* [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is): A string. If specified, the component will behave like a [custom element.](/apis/react-dom/components#custom-html-elements)
* [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id): A string. Specifies a unique identifier for this element, which can be used to find it later or connect it with other elements. Generate it with [`useId`](/reference/react/useId) to avoid clashes between multiple instances of the same component.
* [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is): A string. If specified, the component will behave like a [custom element.](/reference/react-dom/components#custom-html-elements)
* [`inputMode`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode): A string. Specifies what kind of keyboard to display (for example, text, number or telephone).
* [`itemProp`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop): A string. Specifies which property the element represents for structured data crawlers.
* [`lang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang): A string. Specifies the language of the element.
@ -240,7 +240,7 @@ These events fire for resources like [`<audio>`](https://developer.mozilla.org/e
### `ref` callback function {/*ref-callback*/}
Instead of a ref object (like the one returned by [`useRef`](/apis/react/useRef#manipulating-the-dom-with-a-ref)), you may pass a function to the `ref` attribute.
Instead of a ref object (like the one returned by [`useRef`](/reference/react/useRef#manipulating-the-dom-with-a-ref)), you may pass a function to the `ref` attribute.
```js
<div ref={(node) => console.log(node)} />
@ -854,7 +854,7 @@ function Row({ isSelected, size }) {
Sometimes, you'll need to get the browser DOM node associated with a tag in JSX. For example, if you want to focus an `<input>` when a button is clicked, you need to call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the browser `<input>` DOM node.
To obtain the browser DOM node for a tag, [declare a ref](/apis/react/useRef) and pass it as the `ref` attribute to that tag:
To obtain the browser DOM node for a tag, [declare a ref](/reference/react/useRef) and pass it as the `ref` attribute to that tag:
```js {7}
import { useRef } from 'react';
@ -894,7 +894,7 @@ export default function Form() {
</Sandpack>
Read more about [manipulating DOM with refs](/learn/manipulating-the-dom-with-refs) and [check out more examples.](/apis/react/useRef#examples-dom)
Read more about [manipulating DOM with refs](/learn/manipulating-the-dom-with-refs) and [check out more examples.](/reference/react/useRef#examples-dom)
For more advanced use cases, the `ref` attribute also accepts a [callback function.](#ref-callback)

20
beta/src/content/apis/react-dom/components/index.md → beta/src/content/reference/react-dom/components/index.md

@ -14,7 +14,7 @@ React supports all of the browser built-in [HTML](https://developer.mozilla.org/
All of the built-in browser components support some props and events.
* [Common components (e.g. `<div>`)](/apis/react-dom/components/common)
* [Common components (e.g. `<div>`)](/reference/react-dom/components/common)
This includes React-specific props like `ref` and `dangerouslySetInnerHTML`.
@ -24,11 +24,11 @@ This includes React-specific props like `ref` and `dangerouslySetInnerHTML`.
These built-in browser components accept user input:
* [`<input>`](/apis/react-dom/components/input)
* [`<select>`](/apis/react-dom/components/select)
* [`<textarea>`](/apis/react-dom/components/textarea)
* [`<input>`](/reference/react-dom/components/input)
* [`<select>`](/reference/react-dom/components/select)
* [`<textarea>`](/reference/react-dom/components/textarea)
They are special in React because passing the `value` prop to them makes them *[controlled.](/apis/react-dom/components/input#controlling-an-input-with-a-state-variable)*
They are special in React because passing the `value` prop to them makes them *[controlled.](/reference/react-dom/components/input#controlling-an-input-with-a-state-variable)*
---
@ -78,7 +78,7 @@ React supports all built-in browser HTML components. This includes:
* [`<i>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i)
* [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)
* [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)
* [`<input>`](/apis/react-dom/components/input)
* [`<input>`](/reference/react-dom/components/input)
* [`<ins>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins)
* [`<kbd>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd)
* [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)
@ -96,12 +96,12 @@ React supports all built-in browser HTML components. This includes:
* [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object)
* [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol)
* [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup)
* [`<option>`](/apis/react-dom/components/option)
* [`<option>`](/reference/react-dom/components/option)
* [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output)
* [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)
* [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture)
* [`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre)
* [`<progress>`](/apis/react-dom/components/progress)
* [`<progress>`](/reference/react-dom/components/progress)
* [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q)
* [`<rp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rp)
* [`<rt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rt)
@ -110,7 +110,7 @@ React supports all built-in browser HTML components. This includes:
* [`<samp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/samp)
* [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
* [`<section>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section)
* [`<select>`](/apis/react-dom/components/select)
* [`<select>`](/reference/react-dom/components/select)
* [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot)
* [`<small>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small)
* [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source)
@ -124,7 +124,7 @@ React supports all built-in browser HTML components. This includes:
* [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody)
* [`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td)
* [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)
* [`<textarea>`](/apis/react-dom/components/textarea)
* [`<textarea>`](/reference/react-dom/components/textarea)
* [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot)
* [`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th)
* [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead)

16
beta/src/content/apis/react-dom/components/input.md → beta/src/content/reference/react-dom/components/input.md

@ -30,7 +30,7 @@ To display an input, render the [built-in browser `<input>`](https://developer.m
#### Props {/*props*/}
`<input>` supports all [common element props.](/apis/react-dom/components/common#props)
`<input>` supports all [common element props.](/reference/react-dom/components/common#props)
You can [make an input controlled](#controlling-an-input-with-a-state-variable) by passing one of these props:
@ -68,13 +68,13 @@ These `<input>` props are relevant both for uncontrolled and controlled 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)
* `onChange`: An [`Event` handler](/reference/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.
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/reference/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.
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/reference/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).
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event): An [`Event` handler](/reference/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.
@ -150,7 +150,7 @@ input { margin: 5px; }
Typically, you will place every `<input>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that input. When the user clicks the label, the browser will automatically focus the input. It's also essential for accessibility: a screen reader will announce the label caption when the user focuses the associated input.
If you can't nest `<input>` into a `<label>`, associate them by passing the same ID to `<input id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](/apis/react/useId)
If you can't nest `<input>` into a `<label>`, associate them by passing the same ID to `<input id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](/reference/react/useId)
<Sandpack>
@ -305,7 +305,7 @@ By default, *any* `<button>` inside a `<form>` will submit it. This can be surpr
An input like `<input />` is *uncontrolled.* Even if you [pass an initial value](#providing-an-initial-value-for-an-input) like `<input defaultValue="Initial text" />`, your JSX only specifies the initial value. It does not control what the value should be right now.
**To render a _controlled_ input, pass the `value` prop to it (or `checked` for checkboxes and radios).** React will force the input to always have the `value` you passed. Typically, you will control an input by declaring a [state variable:](/apis/react/useState)
**To render a _controlled_ input, pass the `value` prop to it (or `checked` for checkboxes and radios).** React will force the input to always have the `value` you passed. Typically, you will control an input by declaring a [state variable:](/reference/react/useState)
```js {2,6,7}
function Form() {
@ -458,7 +458,7 @@ function SignupForm() {
This significantly improves performance because now only `SignupForm` re-renders on every keystroke.
If there is no way to avoid re-rendering (for example, if `PageContent` depends on the search input's value), [`useDeferredValue`](/apis/react/useDeferredValue#deferring-re-rendering-for-a-part-of-the-ui) lets you keep the controlled input responsive even in the middle of a large re-render.
If there is no way to avoid re-rendering (for example, if `PageContent` depends on the search input's value), [`useDeferredValue`](/reference/react/useDeferredValue#deferring-re-rendering-for-a-part-of-the-ui) lets you keep the controlled input responsive even in the middle of a large re-render.
---

12
beta/src/content/apis/react-dom/components/option.md → beta/src/content/reference/react-dom/components/option.md

@ -4,7 +4,7 @@ title: "<option>"
<Intro>
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) lets you render an option inside a [`<select>`](/apis/react-dom/components/select) box.
The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) lets you render an option inside a [`<select>`](/reference/react-dom/components/select) box.
```js
<select>
@ -23,7 +23,7 @@ The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/
### `<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.
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>`](/reference/react-dom/components/select) box.
```js
<select>
@ -34,17 +34,17 @@ The [built-in browser `<option>` component](https://developer.mozilla.org/en-US/
#### Props {/*props*/}
`<option>` supports all [common element props.](/apis/react-dom/components/common#props)
`<option>` supports all [common element props.](/reference/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.
* [`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](/reference/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.
* React does not support the `selected` attribute on `<option>`. Instead, pass this option's `value` to the parent [`<select defaultValue>`](/reference/react-dom/components/select#providing-an-initially-selected-option) for an uncontrolled select box, or [`<select value>`](/reference/react-dom/components/select#controlling-a-select-box-with-a-state-variable) for a controlled select box.
---
@ -54,7 +54,7 @@ Additionally, `<option>` supports these props:
Render a `<select>` with a list of `<option>` components inside to display a select box. Give each `<option>` a `value` representing the data to be submitted with the form.
[Read more about displaying a `<select>` with a list of `<option>` components.](/apis/react-dom/components/select)
[Read more about displaying a `<select>` with a list of `<option>` components.](/reference/react-dom/components/select)
<Sandpack>

2
beta/src/content/apis/react-dom/components/progress.md → beta/src/content/reference/react-dom/components/progress.md

@ -28,7 +28,7 @@ To display a progress indicator, render the [built-in browser `<progress>`](http
#### Props {/*props*/}
`<progress>` supports all [common element props.](/apis/react-dom/components/common#props)
`<progress>` supports all [common element props.](/reference/react-dom/components/common#props)
Additionally, `<progress>` supports these props:

12
beta/src/content/apis/react-dom/components/select.md → beta/src/content/reference/react-dom/components/select.md

@ -36,7 +36,7 @@ To display a select box, render the [built-in browser `<select>`](https://develo
#### Props {/*props*/}
`<select>` supports all [common element props.](/apis/react-dom/components/common#props)
`<select>` supports all [common element props.](/reference/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:
@ -57,11 +57,11 @@ These `<select>` props are relevant both for uncontrolled and controlled select
* [`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)
* `onChange`: An [`Event` handler](/reference/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.
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/reference/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.
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/reference/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.
@ -111,7 +111,7 @@ select { margin: 5px; }
Typically, you will place every `<select>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that select box. When the user clicks the label, the browser will automatically focus the select box. It's also essential for accessibility: a screen reader will announce the label caption when the user focuses the select box.
If you can't nest `<select>` into a `<label>`, associate them by passing the same ID to `<select id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](/apis/react/useId)
If you can't nest `<select>` into a `<label>`, associate them by passing the same ID to `<select id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between multiple instances of one component, generate such an ID with [`useId`.](/reference/react/useId)
<Sandpack>
@ -302,7 +302,7 @@ By default, *any* `<button>` inside a `<form>` will submit it. This can be surpr
A select box like `<select />` is *uncontrolled.* Even if you [pass an initially selected value](#providing-an-initially-selected-option) like `<select defaultValue="orange" />`, your JSX only specifies the initial value, not the value right now.
**To render a _controlled_ select box, pass the `value` prop to it.** React will force the select box to always have the `value` you passed. Typically, you will control a select box by declaring a [state variable:](/apis/react/useState)
**To render a _controlled_ select box, pass the `value` prop to it.** React will force the select box to always have the `value` you passed. Typically, you will control a select box by declaring a [state variable:](/reference/react/useState)
```js {2,6,7}
function FruitPicker() {

14
beta/src/content/apis/react-dom/components/textarea.md → beta/src/content/reference/react-dom/components/textarea.md

@ -30,7 +30,7 @@ To display a text area, render the [built-in browser `<textarea>`](https://devel
#### Props {/*props*/}
`<textarea>` supports all [common element props.](/apis/react-dom/components/common#props)
`<textarea>` supports all [common element props.](/reference/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:
@ -53,13 +53,13 @@ These `<textarea>` props are relevant both for uncontrolled and controlled text
* [`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)
* `onChange`: An [`Event` handler](/reference/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.
* [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event): An [`Event` handler](/reference/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.
* [`onInvalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event): An [`Event` handler](/reference/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).
* [`onSelect`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement/select_event): An [`Event` handler](/reference/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.
@ -111,7 +111,7 @@ label, textarea { display: block; }
Typically, you will place every `<textarea>` inside a [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) tag. This tells the browser that this label is associated with that text area. When the user clicks the label, the browser will focus the text area. It's also essential for accessibility: a screen reader will announce the label caption when the user focuses the text area.
If you can't nest `<textarea>` into a `<label>`, associate them by passing the same ID to `<textarea id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between instances of one component, generate such an ID with [`useId`.](/apis/react/useId)
If you can't nest `<textarea>` into a `<label>`, associate them by passing the same ID to `<textarea id>` and [`<label htmlFor>`.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement/htmlFor) To avoid conflicts between instances of one component, generate such an ID with [`useId`.](/reference/react/useId)
<Sandpack>
@ -253,7 +253,7 @@ By default, *any* `<button>` inside a `<form>` will submit it. This can be surpr
A text area like `<textarea />` is *uncontrolled.* Even if you [pass an initial value](#providing-an-initial-value-for-a-text-area) like `<textarea defaultValue="Initial text" />`, your JSX only specifies the initial value, not the value right now.
**To render a _controlled_ text area, pass the `value` prop to it.** React will force the text area to always have the `value` you passed. Typically, you will control a text area by declaring a [state variable:](/apis/react/useState)
**To render a _controlled_ text area, pass the `value` prop to it.** React will force the text area to always have the `value` you passed. Typically, you will control a text area by declaring a [state variable:](/reference/react/useState)
```js {2,6,7}
function NewPost() {

4
beta/src/content/apis/react-dom/createPortal.md → beta/src/content/reference/react-dom/createPortal.md

@ -46,7 +46,7 @@ A portal only changes the physical placement of the DOM node. In every other way
#### 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.
* `children`: Anything that can be rendered with React, such as a piece of JSX (e.g. `<div />` or `<SomeComponent />`), a [Fragment](/reference/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.
@ -244,7 +244,7 @@ Follow the [WAI-ARIA Modal Authoring Practices](https://www.w3.org/WAI/ARIA/apg/
### Rendering React components into non-React server markup {/*rendering-react-components-into-non-react-server-markup*/}
Portals can be useful if your React root is only part of a static or server-rendered page that isn't built with React. For example, if your page is built with a server framework like Rails or PHP, you can create areas of interactivity within static areas such as sidebars. Compared with having [multiple separate React roots,](/apis/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) portals let you treat the app as a single React tree with shared state even though its parts render to different parts of the DOM.
Portals can be useful if your React root is only part of a static or server-rendered page that isn't built with React. For example, if your page is built with a server framework like Rails or PHP, you can create areas of interactivity within static areas such as sidebars. Compared with having [multiple separate React roots,](/reference/react-dom/client/createRoot#rendering-a-page-partially-built-with-react) portals let you treat the app as a single React tree with shared state even though its parts render to different parts of the DOM.
<Sandpack>

16
beta/src/content/apis/react-dom/findDOMNode.md → beta/src/content/reference/react-dom/findDOMNode.md

@ -10,7 +10,7 @@ This API will be removed in a future major version of React. [See the alternativ
<Intro>
`findDOMNode` finds the browser DOM node for a React [class component](/apis/react/Component) instance.
`findDOMNode` finds the browser DOM node for a React [class component](/reference/react/Component) instance.
```
const domNode = findDOMNode(componentInstance)
@ -32,7 +32,7 @@ This API will be removed in a future major version of React. [See the alternativ
</Deprecated>
Call `findDOMNode` to find the browser DOM node for a given React [class component](/apis/react/Component) instance.
Call `findDOMNode` to find the browser DOM node for a given React [class component](/reference/react/Component) instance.
```js
const domNode = findDOMNode(componentInstance);
@ -42,7 +42,7 @@ const domNode = findDOMNode(componentInstance);
#### Parameters {/*parameters*/}
* `componentInstance`: An instance of the [`Component`](/apis/react/Component) subclass. For example, `this` inside a class component.
* `componentInstance`: An instance of the [`Component`](/reference/react/Component) subclass. For example, `this` inside a class component.
#### Returns {/*returns*/}
@ -51,7 +51,7 @@ const domNode = findDOMNode(componentInstance);
#### 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.
* A component may return an array or a [Fragment](/reference/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.
@ -71,7 +71,7 @@ This API will be removed in a future major version of React. [See the alternativ
</Deprecated>
Call `findDOMNode` with a [class component](/apis/react/Component) instance (usually, `this`) to find the DOM node it has rendered.
Call `findDOMNode` with a [class component](/reference/react/Component) instance (usually, `this`) to find the DOM node it has rendered.
```js {3}
class AutoselectingInput extends Component {
@ -175,7 +175,7 @@ export default AutoselectingInput;
</Sandpack>
This will break the code because now, `findDOMNode(this)` finds the `<div>` DOM node, but the code expects an `<input>` DOM node. To avoid these kinds of problems, use [`createRef`](/apis/react/createRef) to manage a specific DOM node.
This will break the code because now, `findDOMNode(this)` finds the `<div>` DOM node, but the code expects an `<input>` DOM node. To avoid these kinds of problems, use [`createRef`](/reference/react/createRef) to manage a specific DOM node.
In this example, `findDOMNode` is no longer used. Instead, `inputRef = createRef(null)` is defined as an instance field on the class. To read the DOM node from it, you can use `this.inputRef.current`. To attach it to the JSX, you render `<input ref={this.inputRef} />`. You have connected the code using the DOM node to its JSX:
@ -222,7 +222,7 @@ export default AutoselectingInput;
</Sandpack>
In modern React without class components, the equivalent code would call [`useRef`](/apis/react/useRef) instead:
In modern React without class components, the equivalent code would call [`useRef`](/reference/react/useRef) instead:
<Sandpack>
@ -320,7 +320,7 @@ Notice that calling `findDOMNode(this)` inside `AutoselectingInput` still gives
To replace `findDOMNode` in this example, the two components need to coordinate:
1. `AutoSelectingInput` should declare a ref, like [in the earlier example](#reading-components-own-dom-node-from-a-ref), and pass it to `<MyInput>`.
2. `MyInput` should be declared with [`forwardRef`](/apis/react/forwardRef) to read the passed ref, and pass it down to the `<input>` node.
2. `MyInput` should be declared with [`forwardRef`](/reference/react/forwardRef) to read the passed ref, and pass it down to the `<input>` node.
This version does that, so it no longer needs `findDOMNode`:

0
beta/src/content/apis/react-dom/flushSync.md → beta/src/content/reference/react-dom/flushSync.md

16
beta/src/content/apis/react-dom/hydrate.md → beta/src/content/reference/react-dom/hydrate.md

@ -4,7 +4,7 @@ title: 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)
In React 18, `hydrate` was replaced by [`hydrateRoot`.](/reference/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.
@ -12,7 +12,7 @@ This API will be removed in a future major version of React.
<Intro>
`hydrate` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`](/apis/react-dom/server) in React 17 and below.
`hydrate` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`](/reference/react-dom/server) in React 17 and below.
```js
hydrate(reactNode, domNode, callback?)
@ -30,7 +30,7 @@ hydrate(reactNode, domNode, callback?)
<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)
In React 18, `hydrate` was replaced by [`hydrateRoot`.](/reference/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.
@ -62,7 +62,7 @@ React will attach to the HTML that exists inside the `domNode`, and take over ma
* `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.
* If your app is client-rendered with no HTML rendered already, using `hydrate()` is not supported. Use [render()](/reference/react-dom/render) (for React 17 and below) or [createRoot()](/reference/react-dom/client/createRoot) (for React 18+) instead.
---
@ -76,7 +76,7 @@ import {hydrate} from 'react-dom';
hydrate(<App />, document.getElementById('root'));
````
Using `hydrate()` to render a client-only app (an app without server-rendered HTML) is not supported. Use [`render()`](/apis/react-dom/render) (in React 17 and below) or [`createRoot()`](/apis/react-dom/client/createRoot) (in React 18+) instead.
Using `hydrate()` to render a client-only app (an app without server-rendered HTML) is not supported. Use [`render()`](/reference/react-dom/render) (in React 17 and below) or [`createRoot()`](/reference/react-dom/client/createRoot) (in React 18+) instead.
### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
@ -110,9 +110,9 @@ export default function App() {
</Sandpack>
Usually you shouldn't need to call `hydrate` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
Usually you shouldn't need to call `hydrate` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/reference/react/useState)
For more information on hydration, see the docs for [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot)
For more information on hydration, see the docs for [`hydrateRoot`.](/reference/react-dom/client/hydrateRoot)
---
@ -158,7 +158,7 @@ This only works one level deep, and is intended to be an escape hatch. Don’t o
### Handling different client and server content {/*handling-different-client-and-server-content*/}
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/apis/react/useState) like `isClient`, which you can set to `true` in an [effect](/apis/react/useEffect):
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/reference/react/useState) like `isClient`, which you can set to `true` in an [effect](/reference/react/useEffect):
<Sandpack>

43
beta/src/content/reference/react-dom/index.md

@ -0,0 +1,43 @@
---
title: react-dom
---
<Intro>
The `react-dom` package contains methods that are only supported for the web applications (which run in the browser DOM environment). They are not supported for React Native.
</Intro>
---
## React DOM APIs {/*react-dom-apis*/}
These APIs can be imported from your components. They are rarely used:
* [`createPortal`](/reference/react-dom/createPortal) lets you render child components in a different part of the DOM tree.
* [`flushSync`](/reference/react-dom/flushSync) lets you force React to flush a state update and update the DOM synchronously.
---
## React DOM entry points {/*react-dom-entry-points*/}
The `react-dom` package provides two additional entry points:
* [`react-dom/client`](/reference/react-dom/client) contains APIs to render React components on the client (in the browser).
* [`react-dom/server`](/reference/react-dom/server) contains APIs to render React components on the server.
---
## Deprecated React DOM APIs {/*deprecated-react-dom-apis*/}
<Deprecated>
These APIs will be removed in a future major version of React.
</Deprecated>
* [`findDOMNode`](/reference/react-dom/findDOMNode) finds the closest DOM node corresponding to a class component instance.
* [`hydrate`](/reference/react-dom/hydrate) mounts a tree into the DOM created from server HTML. Deprecated in favor of [`hydrateRoot`](/reference/react-dom/client/hydrateRoot).
* [`render`](/reference/react-dom/render) mounts a tree into the DOM. Deprecated in favor of [`createRoot`](/reference/react-dom/client/createRoot).
* [`unmountComponentAtNode`](/reference/react-dom/unmountComponentAtNode) unmounts a tree from the DOM. Deprecated in favor of [`root.unmount()`.](/reference/react-dom/client/createRoot#root-unmount)

20
beta/src/content/apis/react-dom/render.md → beta/src/content/reference/react-dom/render.md

@ -4,7 +4,7 @@ title: 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)
In React 18, `render` was replaced by [`createRoot`.](/reference/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.
@ -30,7 +30,7 @@ render(reactNode, domNode, callback?)
<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)
In React 18, `render` was replaced by [`createRoot`.](/reference/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.
@ -51,7 +51,7 @@ An app fully built with React will usually only have one `render` call with its
#### 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`.
* `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()`](/reference/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.
@ -64,13 +64,13 @@ An app fully built with React will usually only have one `render` call with its
#### Caveats {/*caveats*/}
* In React 18, `render` was replaced by [`createRoot`.](/apis/react-dom/client/createRoot) Please use `createRoot` for React 18 and beyond.
* In React 18, `render` was replaced by [`createRoot`.](/reference/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.
* 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()`](/reference/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 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](/reference/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`.
* 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`](/reference/react-dom/createPortal) instead of `render`.
---
@ -107,7 +107,7 @@ export default function App() {
</Sandpack>
Usually you shouldn't need to call `render` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
Usually you shouldn't need to call `render` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/reference/react/useState)
---
@ -183,7 +183,7 @@ nav ul li { display: inline-block; margin-right: 20px; }
</Sandpack>
You can destroy the rendered trees with [`unmountComponentAtNode()`.](/apis/react-dom/unmountComponentAtNode)
You can destroy the rendered trees with [`unmountComponentAtNode()`.](/reference/react-dom/unmountComponentAtNode)
---
@ -221,4 +221,4 @@ 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.
It is uncommon to call `render` multiple times. Usually, you'll [update state](/reference/react/useState) inside one of the components instead.

12
beta/src/content/apis/react-dom/server/index.md → beta/src/content/reference/react-dom/server/index.md

@ -14,8 +14,8 @@ The `react-dom/server` APIs let you render React components to HTML on the serve
These methods are only available in the environments with [Node.js Streams:](https://nodejs.org/api/stream.html)
* [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html)
* [`renderToStaticNodeStream`](/apis/react-dom/server/renderToStaticNodeStream) renders a non-interactive React tree to a [Node.js Readable Stream.](https://nodejs.org/api/stream.html#readable-streams)
* [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) renders a React tree to a pipeable [Node.js Stream.](https://nodejs.org/api/stream.html)
* [`renderToStaticNodeStream`](/reference/react-dom/server/renderToStaticNodeStream) renders a non-interactive React tree to a [Node.js Readable Stream.](https://nodejs.org/api/stream.html#readable-streams)
---
@ -23,7 +23,7 @@ These methods are only available in the environments with [Node.js Streams:](htt
These methods are only available in the environments with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), which includes browsers, Deno, and some modern edge runtimes:
* [`renderToReadableStream`](/apis/react-dom/server/renderToReadableStream) renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
* [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) renders a React tree to a [Readable Web Stream.](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
---
@ -31,8 +31,8 @@ These methods are only available in the environments with [Web Streams](https://
These methods can be used in the environments that don't support streams:
* [`renderToString`](/apis/react-dom/server/renderToString) renders a React tree to a string.
* [`renderToStaticMarkup`](/apis/react-dom/server/renderToStaticMarkup) renders a non-interactive React tree to a string.
* [`renderToString`](/reference/react-dom/server/renderToString) renders a React tree to a string.
* [`renderToStaticMarkup`](/reference/react-dom/server/renderToStaticMarkup) renders a non-interactive React tree to a string.
They have limited functionality compared to the streaming APIs.
@ -46,4 +46,4 @@ These APIs will be removed in a future major version of React.
</Deprecated>
* [`renderToNodeStream`](/apis/react-dom/server/renderToNodeStream) renders a React tree to a [Node.js Readable stream.](https://nodejs.org/api/stream.html#readable-streams) (Deprecated.)
* [`renderToNodeStream`](/reference/react-dom/server/renderToNodeStream) renders a React tree to a [Node.js Readable stream.](https://nodejs.org/api/stream.html#readable-streams) (Deprecated.)

14
beta/src/content/apis/react-dom/server/renderToNodeStream.md → beta/src/content/reference/react-dom/server/renderToNodeStream.md

@ -4,7 +4,7 @@ title: renderToNodeStream
<Deprecated>
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) instead.
</Deprecated>
@ -28,7 +28,7 @@ const stream = renderToNodeStream(reactNode)
<Deprecated>
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) instead.
</Deprecated>
@ -39,7 +39,7 @@ const stream = renderToNodeStream(<App />);
stream.pipe(response);
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
@ -51,9 +51,9 @@ A [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams)
#### Caveats {/*caveats*/}
* This method will wait for all [Suspense boundaries](/apis/react/Suspense) to complete before returning any output.
* This method will wait for all [Suspense boundaries](/reference/react/Suspense) to complete before returning any output.
* As of React 18, this method buffers all of its output, so it doesn't actually provide any streaming benefits. This is why it's recommended that you migrate to [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
* As of React 18, this method buffers all of its output, so it doesn't actually provide any streaming benefits. This is why it's recommended that you migrate to [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) instead.
* 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.
@ -65,7 +65,7 @@ A [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams)
<Deprecated>
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
This API will be removed in a future major version of React. Use [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) instead.
</Deprecated>
@ -81,4 +81,4 @@ app.use('/', (request, 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.
The stream will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.

22
beta/src/content/apis/react-dom/server/renderToPipeableStream.md → beta/src/content/reference/react-dom/server/renderToPipeableStream.md

@ -16,7 +16,7 @@ const { pipe, abort } = renderToPipeableStream(reactNode, options?)
<Note>
This API is specific to Node.js. Environments with [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) like Deno and modern edge runtimes, should use [`renderToReadableStream`](/apis/react-dom/server/renderToReadableStream) instead.
This API is specific to Node.js. Environments with [Web Streams,](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) like Deno and modern edge runtimes, should use [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) instead.
</Note>
@ -40,7 +40,7 @@ const { pipe } = renderToPipeableStream(<App />, {
});
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
@ -48,9 +48,9 @@ On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make
* **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** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/reference/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** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/reference/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.
@ -120,7 +120,7 @@ React will automatically inject the [doctype](https://developer.mozilla.org/en-U
<script src="/main.js" async=""></script>
```
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/apis/react-dom/client/hydrateRoot#hydrating-an-entire-document)
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document)
```js [[1, 4, "<App />"]]
import {hydrateRoot} from 'react-dom/client';
@ -230,7 +230,7 @@ function ProfilePage() {
}
```
Imagine that loading data for `<Posts />` takes some time. Ideally, you'd want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](/apis/react/Suspense#displaying-a-fallback-while-content-is-loading)
Imagine that loading data for `<Posts />` takes some time. Ideally, you'd want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading)
```js {9,11}
function ProfilePage() {
@ -251,7 +251,7 @@ function ProfilePage() {
This way, you tell React to start streaming the HTML before `Posts` loads its data. React will send the HTML for the loading fallback (`PostsGlimmer`) first, and then, when `Posts` finishes loading its data, React will send the remaining HTML along with an inline `<script>` tag that replaces the loading fallback with that HTML. From the user's perspective, the page will first appear with the `PostsGlimmer`, and then it will be replaced by the `Posts`.
You can further [nest `<Suspense>` boundaries](/apis/react/Suspense#revealing-nested-content-as-it-loads) to create a more granular loading sequence:
You can further [nest `<Suspense>` boundaries](/reference/react/Suspense#revealing-nested-content-as-it-loads) to create a more granular loading sequence:
```js {5,13}
function ProfilePage() {
@ -283,7 +283,7 @@ Streaming does not need to wait for React itself to load in the browser, or for
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/advanced-features/react-18)
- Lazy-loading component code with [`lazy`](/apis/react/lazy)
- Lazy-loading component code with [`lazy`](/reference/react/lazy)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
@ -426,15 +426,15 @@ function ProfilePage() {
}
```
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
1. It will emit the loading fallback for the closest `<Suspense>` boundary (`PostsGlimmer`) into the HTML.
2. It will "give up" on trying to render the `Posts` content on the server anymore.
3. When the JavaScript code loads on the client, React will *retry* rendering the `Posts` component on the client.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](/apis/react/Component#static-getderivedstatefromerror) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](/reference/react/Component#static-getderivedstatefromerror) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](/apis/react-dom/client/hydrateRoot#hydrateroot) callbacks will fire so that you can get notified about the error.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](/reference/react-dom/client/hydrateRoot#hydrateroot) callbacks will fire so that you can get notified about the error.
---

22
beta/src/content/apis/react-dom/server/renderToReadableStream.md → beta/src/content/reference/react-dom/server/renderToReadableStream.md

@ -16,7 +16,7 @@ const stream = await renderToReadableStream(reactNode, options?)
<Note>
This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) For Node.js, use [`renderToPipeableStream`](/apis/react-dom/server/renderToPipeableStream) instead.
This API depends on [Web Streams.](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) For Node.js, use [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) instead.
</Note>
@ -41,7 +41,7 @@ async function handler(request) {
}
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
@ -49,9 +49,9 @@ On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make
* **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** `bootstrapScripts`: An array of string URLs for the `<script>` tags to emit on the page. Use this to include the `<script>` that calls [`hydrateRoot`.](/reference/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** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as passed to [`hydrateRoot`.](/reference/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.
@ -121,7 +121,7 @@ React will automatically inject the [doctype](https://developer.mozilla.org/en-U
<script src="/main.js" async=""></script>
```
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/apis/react-dom/client/hydrateRoot#hydrating-an-entire-document)
On the client, your bootstrap script should [hydrate the entire `document` with a call to `hydrateRoot`:](/reference/react-dom/client/hydrateRoot#hydrating-an-entire-document)
```js [[1, 4, "<App />"]]
import {hydrateRoot} from 'react-dom/client';
@ -228,7 +228,7 @@ function ProfilePage() {
}
```
Imagine that loading data for `<Posts />` takes some time. Ideally, you'd want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](/apis/react/Suspense#displaying-a-fallback-while-content-is-loading)
Imagine that loading data for `<Posts />` takes some time. Ideally, you'd want to show the rest of the profile page content to the user without waiting for the posts. To do this, [wrap `Posts` in a `<Suspense>` boundary:](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading)
```js {9,11}
function ProfilePage() {
@ -249,7 +249,7 @@ function ProfilePage() {
This way, you tell React to start streaming the HTML before `Posts` loads its data. React will send the HTML for the loading fallback (`PostsGlimmer`) first, and then, when `Posts` finishes loading its data, React will send the remaining HTML along with an inline `<script>` tag that replaces the loading fallback with that HTML. From the user's perspective, the page will first appear with the `PostsGlimmer`, and then it will be replaced by the `Posts`.
You can further [nest `<Suspense>` boundaries](/apis/react/Suspense#revealing-nested-content-as-it-loads) to create a more granular loading sequence:
You can further [nest `<Suspense>` boundaries](/reference/react/Suspense#revealing-nested-content-as-it-loads) to create a more granular loading sequence:
```js {5,13}
function ProfilePage() {
@ -281,7 +281,7 @@ Streaming does not need to wait for React itself to load in the browser, or for
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/advanced-features/react-18)
- Lazy-loading component code with [`lazy`](/apis/react/lazy)
- Lazy-loading component code with [`lazy`](/reference/react/lazy)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
@ -429,15 +429,15 @@ function ProfilePage() {
}
```
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
If an error happens in the `Posts` component or somewhere inside it, React will [try to recover from it:](/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
1. It will emit the loading fallback for the closest `<Suspense>` boundary (`PostsGlimmer`) into the HTML.
2. It will "give up" on trying to render the `Posts` content on the server anymore.
3. When the JavaScript code loads on the client, React will *retry* rendering the `Posts` component on the client.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](/apis/react/Component#static-getderivedstatefromerror) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client *also* fails, React will throw the error on the client. As with all the errors thrown during rendering, the [closest parent error boundary](/reference/react/Component#static-getderivedstatefromerror) determines how to present the error to the user. In practice, this means that the user will see a loading indicator until it is certain that the error is not recoverable.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](/apis/react-dom/client/hydrateRoot#hydrateroot) callbacks will fire so that you can get notified about the error.
If retrying rendering `Posts` on the client succeeds, the loading fallback from the server will be replaced with the client rendering output. The user will not know that there was a server error. However, the server `onError` callback and the client [`onRecoverableError`](/reference/react-dom/client/hydrateRoot#hydrateroot) callbacks will fire so that you can get notified about the error.
---

4
beta/src/content/apis/react-dom/server/renderToStaticMarkup.md → beta/src/content/reference/react-dom/server/renderToStaticMarkup.md

@ -42,7 +42,7 @@ An HTML string.
* `renderToStaticMarkup` has limited Suspense support. If a component suspends, `renderToStaticMarkup` immediately sends its fallback as HTML.
* `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)
* `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.](/reference/react-dom/server/renderToString#removing-rendertostring-from-the-client-code)
---
@ -68,6 +68,6 @@ This will produce the initial non-interactive HTML output of your React componen
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.
Interactive apps should use [`renderToString`](/reference/react-dom/server/renderToString) on the server and [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) on the client.
</Pitfall>

4
beta/src/content/apis/react-dom/server/renderToStaticNodeStream.md → beta/src/content/reference/react-dom/server/renderToStaticNodeStream.md

@ -41,7 +41,7 @@ A [Node.js Readable Stream](https://nodejs.org/api/stream.html#readable-streams)
* `renderToStaticNodeStream` output cannot be hydrated.
* This method will wait for all [Suspense boundaries](/apis/react/Suspense) to complete before returning any output.
* This method will wait for all [Suspense boundaries](/reference/react/Suspense) to complete before returning any output.
* As of React 18, this method buffers all of its output, so it doesn't actually provide any streaming benefits.
@ -69,7 +69,7 @@ The stream will produce the initial non-interactive HTML output of your React co
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.
Interactive apps should use [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream) on the server and [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) on the client.
</Pitfall>

14
beta/src/content/apis/react-dom/server/renderToString.md → beta/src/content/reference/react-dom/server/renderToString.md

@ -32,7 +32,7 @@ On the server, call `renderToString` to render your app to HTML.
const html = renderToString(<App />);
```
On the client, call [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
#### Parameters {/*parameters*/}
@ -66,7 +66,7 @@ app.use('/', (request, response) => {
});
```
This 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.
This will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.
<Pitfall>
@ -85,8 +85,8 @@ This will produce the initial non-interactive HTML output of your React componen
When possible, we recommend to use these fully-featured alternatives:
* If you use Node.js, use [`renderToPipeableStream`.](/apis/react-dom/server/renderToPipeableStream)
* If you use Deno or a modern edge runtime with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), use [`renderToReadableStream`.](/apis/react-dom/server/renderToReadableStream)
* If you use Node.js, use [`renderToPipeableStream`.](/reference/react-dom/server/renderToPipeableStream)
* If you use Deno or a modern edge runtime with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), use [`renderToReadableStream`.](/reference/react-dom/server/renderToReadableStream)
You can continue using `renderToString` if your server environment does not support streams.
@ -104,7 +104,7 @@ const html = renderToString(<MyIcon />);
console.log(html); // For example, "<svg>...</svg>"
```
Importing `react-dom/server` **on the client** unnecessarily increases your bundle size and should be avoided. If you need to render some component to HTML in the browser, use [`createRoot`](/apis/react-dom/client/createRoot) and read HTML from the DOM:
Importing `react-dom/server` **on the client** unnecessarily increases your bundle size and should be avoided. If you need to render some component to HTML in the browser, use [`createRoot`](/reference/react-dom/client/createRoot) and read HTML from the DOM:
```js
import { createRoot } from 'react-dom/client';
@ -118,7 +118,7 @@ flushSync(() => {
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.
The [`flushSync`](/reference/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.
---
@ -128,7 +128,7 @@ The [`flushSync`](/apis/react-dom/flushSync) call is necessary so that the DOM i
`renderToString` does not fully support Suspense.
If some component suspends (for example, because it's defined with [`lazy`](/apis/react/lazy) or fetches data), `renderToString` will not wait for its content to resolve. Instead, `renderToString` will find the closest [`<Suspense>`](/apis/react/Suspense) boundary above it and render its `fallback` prop in the HTML. The content will not appear until the client code loads.
If some component suspends (for example, because it's defined with [`lazy`](/reference/react/lazy) or fetches data), `renderToString` will not wait for its content to resolve. Instead, `renderToString` will find the closest [`<Suspense>`](/reference/react/Suspense) boundary above it and render its `fallback` prop in the HTML. The content will not appear until the client code loads.
To solve this, use one of the [recommended streaming solutions.](#migrating-from-rendertostring-to-a-streaming-method-on-the-server) They can stream content in chunks as it resolves on the server so that the user sees the page being progressively filled in even before the client code loads.

4
beta/src/content/apis/react-dom/unmountComponentAtNode.md → beta/src/content/reference/react-dom/unmountComponentAtNode.md

@ -4,7 +4,7 @@ title: unmountComponentAtNode
<Deprecated>
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/apis/react-dom/client/createRoot#root-unmount).
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/reference/react-dom/client/createRoot#root-unmount).
This API will be removed in a future major version of React.
@ -30,7 +30,7 @@ unmountComponentAtNode(domNode)
<Deprecated>
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/apis/react-dom/client/createRoot#root-unmount).
In React 18, `unmountComponentAtNode` was replaced by [`root.unmount()`](/reference/react-dom/client/createRoot#root-unmount).
This API will be removed in a future major version of React.

8
beta/src/content/apis/react/Children.md → beta/src/content/reference/react/Children.md

@ -58,7 +58,7 @@ 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.
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/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](/reference/react/Fragment) don't get traversed.
---
@ -92,7 +92,7 @@ function SeparatorList({ children }) {
#### 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.
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/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](/reference/react/Fragment) don't get traversed.
---
@ -132,7 +132,7 @@ Otherwise, returns a flat array consisting of the nodes you've returned from the
#### 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.
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/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](/reference/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.
@ -155,7 +155,7 @@ function Box({ children }) {
#### Returns {/*children-only-returns*/}
If `children` [is a valid element,](/apis/react/isValidElement) returns that element.
If `children` [is a valid element,](/reference/react/isValidElement) returns that element.
Otherwise, throws an error.

68
beta/src/content/apis/react/Component.md → beta/src/content/reference/react/Component.md

@ -79,7 +79,7 @@ class Button extends Component {
<Note>
Reading `this.context` in class components is equivalent to [`useContext`](/apis/react/useContext) in function components.
Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components.
[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function)
@ -115,7 +115,7 @@ Reading `this.props` in class components is equivalent to [declaring props](/lea
<Deprecated>
This API will be removed in a future major version of React. [Use `createRef` instead.](/apis/react/createRef)
This API will be removed in a future major version of React. [Use `createRef` instead.](/reference/react/createRef)
</Deprecated>
@ -154,7 +154,7 @@ class Counter extends Component {
<Note>
Defining `state` in class components is equivalent to calling [`useState`](/apis/react/useState) in function components.
Defining `state` in class components is equivalent to calling [`useState`](/reference/react/useState) in function components.
[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function)
@ -208,13 +208,13 @@ A constructor should not contain any side effects or subscriptions.
* Constructor is the only place where you can assign [`this.state`](#state) directly. In all other methods, you need to use [`this.setState()`](#setstate) instead. Do not call `setState` in the constructor.
* When you use [server rendering,](/apis/react-dom/server) the constructor will run on the server too, followed by the [`render`](#render) method. However, lifecycle methods like `componentDidMount` or `componentWillUnmount` will not run on the server.
* When you use [server rendering,](/reference/react-dom/server) the constructor will run on the server too, followed by the [`render`](#render) method. However, lifecycle methods like `componentDidMount` or `componentWillUnmount` will not run on the server.
* When [Strict Mode](/apis/react/StrictMode) is on, React will call `constructor` twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the `constructor`.
* When [Strict Mode](/reference/react/StrictMode) is on, React will call `constructor` twice in development and then throw away one of the instances. This helps you notice the accidental side effects that need to be moved out of the `constructor`.
<Note>
There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/apis/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/apis/react/useState#avoiding-recreating-the-initial-state)
There is no exact equivalent for `constructor` in function components. To declare state in a function component, call [`useState`.](/reference/react/useState) To avoid recalculating the initial state, [pass a function to `useState`.](/reference/react/useState#avoiding-recreating-the-initial-state)
</Note>
@ -340,13 +340,13 @@ class ChatRoom extends Component {
#### Caveats {/*componentdidmount-caveats*/}
- When [Strict Mode](/apis/react/StrictMode) is on, in development React will call `componentDidMount`, then immediately call [`componentWillUnmount`,](#componentwillunmount) and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call `componentDidMount`, then immediately call [`componentWillUnmount`,](#componentwillunmount) and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
- Although you may call [`setState`](#setstate) immediately in `componentDidMount`, it's best to avoid that when you can. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the [`render`](#render) will be called twice in this case, the user won't see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the [`constructor`](#constructor) instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
<Note>
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/apis/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/apis/react/useLayoutEffect) is a closer match.
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match.
[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function)
@ -413,7 +413,7 @@ class ChatRoom extends Component {
<Note>
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/apis/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/apis/react/useLayoutEffect) is a closer match.
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match.
[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function)
@ -502,11 +502,11 @@ class ChatRoom extends Component {
#### Caveats {/*componentwillunmount-caveats*/}
- When [Strict Mode](/apis/react/StrictMode) is on, in development React will call [`componentDidMount`,](#componentdidmount) then immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
- When [Strict Mode](/reference/react/StrictMode) is on, in development React will call [`componentDidMount`,](#componentdidmount) then immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
<Note>
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/apis/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/apis/react/useLayoutEffect) is a closer match.
For many use cases, defining `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` together in class components is equivalent to calling [`useEffect`](/reference/react/useEffect) in function components. In the rare cases where it's important for the code to run before browser paint, [`useLayoutEffect`](/reference/react/useLayoutEffect) is a closer match.
[See how to migrate.](#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function)
@ -536,7 +536,7 @@ Try to avoid all uses of `forceUpdate` and only read from `this.props` and `this
<Note>
Reading an external data source and forcing class components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/apis/react/useSyncExternalStore) in function components.
Reading an external data source and forcing class components to re-render in response to its changes with `forceUpdate` has been superseded by [`useSyncExternalStore`](/reference/react/useSyncExternalStore) in function components.
</Note>
@ -546,7 +546,7 @@ Reading an external data source and forcing class components to re-render in res
<Deprecated>
This API will be removed in a future major version of React. [Use `Context.Provider` instead.](/apis/react/createContext#provider)
This API will be removed in a future major version of React. [Use `Context.Provider` instead.](/reference/react/createContext#provider)
</Deprecated>
@ -647,7 +647,7 @@ You should write the `render` method as a pure function, meaning that it should
#### Returns {/*render-returns*/}
`render` can return any valid React node. This includes React elements such as `<div />`, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
`render` can return any valid React node. This includes React elements such as `<div />`, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
#### Caveats {/*render-caveats*/}
@ -655,7 +655,7 @@ You should write the `render` method as a pure function, meaning that it should
- `render` will not get called if [`shouldComponentUpdate`](#shouldcomponentupdate) is defined and returns `false`.
- When [Strict Mode](/apis/react/StrictMode) is on, React will call `render` twice in development and then throw away one of the results. This helps you notice the accidental side effects that need to be moved out of the `render` method.
- When [Strict Mode](/reference/react/StrictMode) is on, React will call `render` twice in development and then throw away one of the results. This helps you notice the accidental side effects that need to be moved out of the `render` method.
- There is no one-to-one correspondence between the `render` call and the subsequent `componentDidMount` or `componentDidUpdate` call. Some of the `render` call results may be discarded by React when it's beneficial.
@ -737,13 +737,13 @@ You don't have to do this, but it's handy if you want to update state multiple t
#### Caveats {/*setstate-caveats*/}
- Think of `setState` as a *request* rather than an immediate command to update the component. When multiple components update their state in response to an event, React will batch their updates and re-render them together in a single pass at the end of the event. In the rare case that you need to force a particular state update to be applied synchronously, you may wrap it in [`flushSync`,](/apis/react-dom/flushSync) but this may hurt performance.
- Think of `setState` as a *request* rather than an immediate command to update the component. When multiple components update their state in response to an event, React will batch their updates and re-render them together in a single pass at the end of the event. In the rare case that you need to force a particular state update to be applied synchronously, you may wrap it in [`flushSync`,](/reference/react-dom/flushSync) but this may hurt performance.
- `setState` does not update `this.state` immediately. This makes reading `this.state` right after calling `setState` a potential pitfall. Instead, use [`componentDidUpdate`](#componentdidupdate) or the setState `callback` argument, either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, you can pass a function to `nextState` as described above.
<Note>
Calling `setState` in class components is similar to calling a [`set` function](/apis/react/useState#setstate) in function components.
Calling `setState` in class components is similar to calling a [`set` function](/reference/react/useState#setstate) in function components.
[See how to migrate.](#migrating-a-component-with-state-from-a-class-to-a-function)
@ -800,7 +800,7 @@ Return `false` to tell React that re-rendering can be skipped.
- This method *only* exists as a performance optimization. If your component breaks without it, fix that first.
- Consider using [`PureComponent`](/apis/react/PureComponent) instead of writing `shouldComponentUpdate` by hand. `PureComponent` shallowly compares props and state, and reduces the chance that you'll skip a necessary update.
- Consider using [`PureComponent`](/reference/react/PureComponent) instead of writing `shouldComponentUpdate` by hand. `PureComponent` shallowly compares props and state, and reduces the chance that you'll skip a necessary update.
- We do not recommend doing deep equality checks or using `JSON.stringify` in `shouldComponentUpdate`. It makes performance unpredictable and dependent on the data structure of every prop and state. In the best case, you risk introducing multi-second stalls to your application, and in the worst case you risk crashing it.
@ -810,7 +810,7 @@ Return `false` to tell React that re-rendering can be skipped.
<Note>
Optimizing class components with `shouldComponentUpdate` is similar to optimizing function components with [`memo`.](/apis/react/memo) Function components also offer more granular optimization with [`useMemo`.](/apis/react/useMemo)
Optimizing class components with `shouldComponentUpdate` is similar to optimizing function components with [`memo`.](/reference/react/memo) Function components also offer more granular optimization with [`useMemo`.](/reference/react/useMemo)
</Note>
@ -837,13 +837,13 @@ If you define `UNSAFE_componentWillMount`, React will call it immediately after
- `UNSAFE_componentWillMount` will not get called if the component implements [`static getDerivedStateFromProps`](getDerivedStateFromProps) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate)
- Despite its naming, `UNSAFE_componentWillMount` does not guarantee that the component *will* get mounted if your app uses modern React features like [`Suspense`.](/apis/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. This is why this method is "unsafe". Code that relies on mounting (like adding a subscription) should go into [`componentDidMount`.](#componentdidmount)
- Despite its naming, `UNSAFE_componentWillMount` does not guarantee that the component *will* get mounted if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. This is why this method is "unsafe". Code that relies on mounting (like adding a subscription) should go into [`componentDidMount`.](#componentdidmount)
- `UNSAFE_componentWillMount` is the only lifecycle method that runs during [server rendering.](/apis/react-dom/server) For all practical purposes, it is identical to [`constructor`,](#constructor) so you should use the `constructor` for this type of logic instead.
- `UNSAFE_componentWillMount` is the only lifecycle method that runs during [server rendering.](/reference/react-dom/server) For all practical purposes, it is identical to [`constructor`,](#constructor) so you should use the `constructor` for this type of logic instead.
<Note>
Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class component to initialize state is equivalent to passing that state as the initial state to [`useState`](/apis/react/useState) in a function component.
Calling [`setState`](#setstate) inside `UNSAFE_componentWillMount` in a class component to initialize state is equivalent to passing that state as the initial state to [`useState`](/reference/react/useState) in a function component.
</Note>
@ -856,7 +856,7 @@ If you define `UNSAFE_componentWillReceiveProps`, React will call it when the co
- If you need to **run a side effect** (for example, fetch data, run an animation, or reinitialize a subscription) in response to prop changes, move that logic to [`componentDidUpdate`](#componentdidupdate) instead.
- If you need to **avoid re-computing some data only when a prop changes,** use a [memoization helper](/blog/2018/06/07/you-probably-dont-need-derived-state#what-about-memoization) instead.
- If you need to **"reset" some state when a prop changes,** consider either making a component [fully controlled](/blog/2018/06/07/you-probably-dont-need-derived-state#recommendation-fully-controlled-component) or [fully uncontrolled with a key](/blog/2018/06/07/you-probably-dont-need-derived-state#recommendation-fully-uncontrolled-component-with-a-key) instead.
- If you need to **"adjust" some state when a prop changes,** check whether you can compute all the necessary information from props alone during rendering. If you can't, use [`static getDerivedStateFromProps`](/apis/react/Component#static-getderivedstatefromprops) instead.
- If you need to **"adjust" some state when a prop changes,** check whether you can compute all the necessary information from props alone during rendering. If you can't, use [`static getDerivedStateFromProps`](/reference/react/Component#static-getderivedstatefromprops) instead.
[See examples of migrating away from unsafe lifecycles.](/blog/2018/03/27/update-on-async-rendering#updating-state-based-on-props)
@ -873,7 +873,7 @@ If you define `UNSAFE_componentWillReceiveProps`, React will call it when the co
- `UNSAFE_componentWillReceiveProps` will not get called if the component implements [`static getDerivedStateFromProps`](getDerivedStateFromProps) or [`getSnapshotBeforeUpdate`.](#getsnapshotbeforeupdate)
- Despite its naming, `UNSAFE_componentWillReceiveProps` does not guarantee that the component *will* receive those props if your app uses modern React features like [`Suspense`.](/apis/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate)
- Despite its naming, `UNSAFE_componentWillReceiveProps` does not guarantee that the component *will* receive those props if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate)
- `UNSAFE_componentWillReceiveProps` does not mean that the component has received *different* props than the last time. You need to compare `nextProps` and `this.props` yourself to check if something changed.
@ -881,7 +881,7 @@ If you define `UNSAFE_componentWillReceiveProps`, React will call it when the co
<Note>
Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a class component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/apis/react/useState#storing-information-from-previous-renders) in a function component.
Calling [`setState`](#setstate) inside `UNSAFE_componentWillReceiveProps` in a class component to "adjust" state is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component.
</Note>
@ -914,7 +914,7 @@ If you define `UNSAFE_componentWillUpdate`, React will call it before rendering
- It's not supported to call [`setState`](#setstate) (or any method that leads to `setState` being called, like dispatching a Redux action) during `componentWillUpdate`.
- Despite its naming, `UNSAFE_componentWillUpdate` does not guarantee that the component *will* update if your app uses modern React features like [`Suspense`.](/apis/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props and state might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate)
- Despite its naming, `UNSAFE_componentWillUpdate` does not guarantee that the component *will* update if your app uses modern React features like [`Suspense`.](/reference/react/Suspense) If a render attempt is suspended (for example, because the code for some child component has not loaded yet), React will throw the in-progress tree away and attempt to construct the component from scratch during the next attempt. By the time of the next render attempt, the props and state might be different. This is why this method is "unsafe". Code that should run only for committed updates (like resetting a subscription) should go into [`componentDidUpdate`.](#componentdidupdate)
- `UNSAFE_componentWillUpdate` does not mean that the component has received *different* props or state than the last time. You need to compare `nextProps` with `this.props` and `nextState` with `this.state` yourself to check if something changed.
@ -954,7 +954,7 @@ Lets you specify which [legacy context](https://reactjs.org/docs/legacy-context.
### `static contextType` {/*static-contexttype*/}
If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which context it needs to read. The context you specify as the `static contextType` must be a value previously created by [`createContext`.](/apis/react/createContext)
If you want to read [`this.context`](#context-instance-field) from your class component, you must specify which context it needs to read. The context you specify as the `static contextType` must be a value previously created by [`createContext`.](/reference/react/createContext)
```js {2}
class Button extends Component {
@ -974,7 +974,7 @@ class Button extends Component {
<Note>
Reading `this.context` in class components is equivalent to [`useContext`](/apis/react/useContext) in function components.
Reading `this.context` in class components is equivalent to [`useContext`](/reference/react/useContext) in function components.
[See how to migrate.](#migrating-a-component-with-context-from-a-class-to-a-function)
@ -1149,7 +1149,7 @@ Deriving state leads to verbose code and makes your components difficult to thin
<Note>
Implementing `static getDerivedStateFromProps` in a class component is equivalent to [calling the `set` function from `useState` during rendering](/apis/react/useState#storing-information-from-previous-renders) in a function component.
Implementing `static getDerivedStateFromProps` in a class component is equivalent to [calling the `set` function from `useState` during rendering](/reference/react/useState#storing-information-from-previous-renders) in a function component.
</Note>
@ -1199,7 +1199,7 @@ export default function App() {
</Sandpack>
Note that Hooks (functions starting with `use`, like [`useState`](/apis/react/useState)) are not supported inside class components.
Note that Hooks (functions starting with `use`, like [`useState`](/reference/react/useState)) are not supported inside class components.
<Pitfall>
@ -1391,7 +1391,7 @@ button { margin-left: 10px; }
</Sandpack>
Note that in development when [Strict Mode](/apis/react/StrictMode) is on, React will call `componentDidMount`, immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
Note that in development when [Strict Mode](/reference/react/StrictMode) is on, React will call `componentDidMount`, immediately call `componentWillUnmount`, and then call `componentDidMount` again. This helps you notice if you forgot to implement `componentWillUnmount` or if its logic doesn't fully "mirror" what `componentDidMount` does.
<Pitfall>
@ -1523,7 +1523,7 @@ button { display: block; margin-top: 10px; }
</Sandpack>
Start by declaring a function with the necessary [state variables:](/apis/react/useState#adding-state-to-a-component)
Start by declaring a function with the necessary [state variables:](/reference/react/useState#adding-state-to-a-component)
```js {4-5}
import { useState } from 'react';
@ -1717,7 +1717,7 @@ First, verify that your [`componentWillUnmount`](#componentwillunmount) does the
Next, verify that your [`componentDidUpdate`](#componentdidupdate) method handles changes to any props and state you're using in `componentDidMount`. In the above example, `componentDidMount` calls `setupConnection` which reads `this.state.serverUrl` and `this.props.roomId`. This is why `componentDidUpdate` checks whether `this.state.serverUrl` and `this.props.roomId` have changed, and resets the connection if they did. If your `componentDidUpdate` logic is missing or doesn't handle changes to all relevant props and state, fix that first.
In the above example, the logic inside the lifecycle methods connects the component to a system outside of React (a chat server). To connect a component to an external system, [describe this logic as a single Effect:](/apis/react/useEffect#connecting-to-an-external-system)
In the above example, the logic inside the lifecycle methods connects the component to a system outside of React (a chat server). To connect a component to an external system, [describe this logic as a single Effect:](/reference/react/useEffect#connecting-to-an-external-system)
```js {6-12}
import { useState, useEffect } from 'react';
@ -1926,7 +1926,7 @@ export default function MyApp() {
</Sandpack>
When you convert them to function components, replace `this.context` with [`useContext`](/apis/react/useContext) calls:
When you convert them to function components, replace `this.context` with [`useContext`](/reference/react/useContext) calls:
<Sandpack>

0
beta/src/content/apis/react/Fragment.md → beta/src/content/reference/react/Fragment.md

2
beta/src/content/apis/react/Profiler.md → beta/src/content/reference/react/Profiler.md

@ -55,7 +55,7 @@ function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime
* `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.
* `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`](/reference/react/memo) and [`useMemo`](/reference/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.

14
beta/src/content/apis/react/PureComponent.md → beta/src/content/reference/react/PureComponent.md

@ -10,7 +10,7 @@ We recommend to define components as functions instead of classes. [See how to m
<Intro>
`PureComponent` is similar to [`Component`](/apis/react/Component) but it skips re-renders for same props and state. Class components are still supported by React, but we don't recommend using them in new code.
`PureComponent` is similar to [`Component`](/reference/react/Component) but it skips re-renders for same props and state. Class components are still supported by React, but we don't recommend using them in new code.
```js
class Greeting extends PureComponent {
@ -30,7 +30,7 @@ class Greeting extends PureComponent {
### `PureComponent` {/*purecomponent*/}
To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/apis/react/Component)
To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/reference/react/Component)
```js
import { PureComponent } from 'react';
@ -42,7 +42,7 @@ class Greeting extends PureComponent {
}
```
`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.
`PureComponent` is a subclass of `Component` and supports [all the `Component` APIs.](/reference/react/Component#reference) Extending `PureComponent` is equivalent to defining a custom [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) method that shallowly compares props and state.
[See more examples below.](#usage)
@ -53,7 +53,7 @@ class Greeting extends PureComponent {
### Skipping unnecessary re-renders for class components {/*skipping-unnecessary-re-renders-for-class-components*/}
React normally re-renders a component whenever its parent re-renders. As an optimization, you can create a component that React will not re-render when its parent re-renders so long as its new props and state are the same as the old props and state. [Class components](/apis/react/Component) can opt into this behavior by extending `PureComponent`:
React normally re-renders a component whenever its parent re-renders. As an optimization, you can create a component that React will not re-render when its parent re-renders so long as its new props and state are the same as the old props and state. [Class components](/reference/react/Component) can opt into this behavior by extending `PureComponent`:
```js {1}
class Greeting extends PureComponent {
@ -119,7 +119,7 @@ We recommend to define components as functions instead of classes. [See how to m
### Migrating from a `PureComponent` class component to a function {/*migrating-from-a-purecomponent-class-component-to-a-function*/}
We recommend to use function components instead of [class components](/apis/react/Component) in the new code. If you have some existing class components using `PureComponent`, here is how you can convert them. This is the original code:
We recommend to use function components instead of [class components](/reference/react/Component) in the new code. If you have some existing class components using `PureComponent`, here is how you can convert them. This is the original code:
<Sandpack>
@ -161,7 +161,7 @@ label {
</Sandpack>
When you [convert this component from a class to a function,](/apis/react/Component#alternatives) wrap it in [`memo`:](/apis/react/memo)
When you [convert this component from a class to a function,](/reference/react/Component#alternatives) wrap it in [`memo`:](/reference/react/memo)
<Sandpack>
@ -203,6 +203,6 @@ label {
<Note>
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`.
Unlike `PureComponent`, [`memo`](/reference/react/memo) does not compare the new and the old state. In function components, calling the [`set` function](/reference/react/useState#setstate) with the same state [already prevents re-renders by default,](/reference/react/memo#updating-a-memoized-component-using-state) even without `memo`.
</Note>

16
beta/src/content/apis/react/StrictMode.md → beta/src/content/reference/react/StrictMode.md

@ -77,7 +77,7 @@ root.render(
);
```
We recommend to wrap your entire app in Strict Mode, especially for newly created apps. If you use a framework that calls [`createRoot`](/apis/react/createRoot) for you, check its documentation for how to enable Strict Mode.
We recommend to wrap your entire app in Strict Mode, especially for newly created apps. If you use a framework that calls [`createRoot`](/reference/react/createRoot) for you, check its documentation for how to enable Strict Mode.
Although the Strict Mode checks **only run in development,** they help you find bugs that already exist in your code but can be tricky to reliably reproduce in production. Strict Mode lets you fix bugs before your users report them.
@ -129,8 +129,8 @@ In this example, Strict Mode checks will not run against the `Header` and `Foote
Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) **twice in development.** This includes:
- Your component function body (only top-level logic, so this doesn't include code inside event handlers)
- Functions that you pass to [`useState`](/apis/react/useState), [`set` functions](/apis/react/useState#setstate), [`useMemo`](/apis/react/useMemo), or [`useReducer`](/apis/react/useReducer)
- Some class component methods like [`constructor`](/apis/react/Component#constructor), [`render`](/apis/react/Component#render), [`shouldComponentUpdate`](/apis/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects))
- Functions that you pass to [`useState`](/reference/react/useState), [`set` functions](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), or [`useReducer`](/reference/react/useReducer)
- Some class component methods like [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects))
If a function is pure, running it twice does not change its behavior because a pure function produces the same result every time. However, if a function is impure (for example, it mutates the data it receives), running that impure code twice tends to be noticeable (that's what makes it impure!) This helps you spot and fix the bug early.
@ -822,9 +822,9 @@ Without Strict Mode, it was easy to miss that your Effect needed cleanup. By run
React warns if some component anywhere inside a `<StrictMode>` tree uses one of these deprecated APIs:
* [`findDOMNode`](/apis/react-dom/findDOMNode). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)
* `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](/apis/react/Component#unsafe_componentwillmount). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles)
* Legacy context ([`childContextTypes`](/apis/react/Component#static-childcontexttypes), [`contextTypes`](/apis/react/Component#static-contexttypes), and [`getChildContext`](/apis/react/Component#getchildcontext)). [See alternatives.](/apis/react/createContext)
* 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)
* [`findDOMNode`](/reference/react-dom/findDOMNode). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage)
* `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles)
* Legacy context ([`childContextTypes`](/reference/react/Component#static-childcontexttypes), [`contextTypes`](/reference/react/Component#static-contexttypes), and [`getChildContext`](/reference/react/Component#getchildcontext)). [See alternatives.](/reference/react/createContext)
* Legacy string refs ([`this.refs`](/reference/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.
These APIs are primarily used in older [class components](/reference/react/Component) so they rarely appear in modern apps.

20
beta/src/content/apis/react/Suspense.md → beta/src/content/reference/react/Suspense.md

@ -30,8 +30,8 @@ title: <Suspense>
#### 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.
- 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`](/reference/react/startTransition) or [`useDeferredValue`](/reference/react/useDeferredValue).
- If React needs to hide the already visible content because it suspended again, it will clean up [layout Effects](/reference/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.
---
@ -253,7 +253,7 @@ async function getAlbums() {
**Only Suspense-enabled data sources will activate the Suspense component.** They include:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/advanced-features/react-18)
- Lazy-loading component code with [`lazy`](/apis/react/lazy)
- Lazy-loading component code with [`lazy`](/reference/react/lazy)
Suspense **does not** detect when data is fetched inside an Effect or event handler.
@ -1116,7 +1116,7 @@ input { margin: 10px; }
</Sandpack>
A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](/apis/react/useDeferredValue) Hook lets you pass a deferred version of the query down:
A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](/reference/react/useDeferredValue) Hook lets you pass a deferred version of the query down:
```js {3,11}
export default function App() {
@ -1726,7 +1726,7 @@ main {
When you pressed the button, the `Router` component rendered `ArtistPage` instead of `IndexPage`. A component inside the `ArtistPage` suspended, so the closest Suspense boundary started showing the fallback. The closest Suspense boundary was near the root, so the whole site layout got replaced by `BigSpinner`.
To prevent this from happening, you can mark the navigation state update as a *transition* with [`startTransition`:](/apis/react/startTransition)
To prevent this from happening, you can mark the navigation state update as a *transition* with [`startTransition`:](/reference/react/startTransition)
```js {5,7}
function Router() {
@ -2123,7 +2123,7 @@ Suspense-enabled routers are expected to wrap the navigation updates into transi
### Indicating that a transition is happening {/*indicating-that-a-transition-is-happening*/}
In the above example, once you click the button, there is no visual indication that a navigation is in progress. To add an indicator, you can replace [`startTransition`](/apis/react/startTransition) with [`useTransition`](/apis/react/useTransition) which gives you a boolean `isPending` value. In the example below, it's used to change the website header styling while a transition is happening:
In the above example, once you click the button, there is no visual indication that a navigation is in progress. To add an indicator, you can replace [`startTransition`](/reference/react/startTransition) with [`useTransition`](/reference/react/useTransition) which gives you a boolean `isPending` value. In the example below, it's used to change the website header styling while a transition is happening:
<Sandpack>
@ -2515,9 +2515,9 @@ However, now imagine you're navigating between two different user profiles. In t
### Providing a fallback for server errors and server-only content {/*providing-a-fallback-for-server-errors-and-server-only-content*/}
If you use one of the [streaming server rendering APIs](/apis/react-dom/server) (or a framework that relies on them), React will also use your `<Suspense>` boundaries to handle errors on the server. If a component throws an error on the server, React will not abort the server render. Instead, it will find the closest `<Suspense>` component above it and include its fallback (such as a spinner) into the generated server HTML. The user will see a spinner instead of an error.
If you use one of the [streaming server rendering APIs](/reference/react-dom/server) (or a framework that relies on them), React will also use your `<Suspense>` boundaries to handle errors on the server. If a component throws an error on the server, React will not abort the server render. Instead, it will find the closest `<Suspense>` component above it and include its fallback (such as a spinner) into the generated server HTML. The user will see a spinner instead of an error.
On the client, React will attempt to render the same component again. If it errors on the client too, React will throw the error and display the closest [error boundary.](/apis/react/Component#static-getderivedstatefromerror) However, if it does not error on the client, React will not display the error to the user since the content was eventually displayed successfully.
On the client, React will attempt to render the same component again. If it errors on the client too, React will throw the error and display the closest [error boundary.](/reference/react/Component#static-getderivedstatefromerror) However, if it does not error on the client, React will not display the error to the user since the content was eventually displayed successfully.
You can use this to opt out some components from rendering on the server. To do this, throw an error from them in the server environment and then wrap them in a `<Suspense>` boundary to replace their HTML with fallbacks:
@ -2557,6 +2557,6 @@ function handleNextPageClick() {
This will avoid hiding existing content. However, any newly rendered `Suspense` boundaries will still immediately display fallbacks to avoid blocking the UI and let the user see the content as it becomes available.
**React will only prevent unwanted fallbacks during non-urgent updates**. It will not delay a render if it's the result of an urgent update. You must opt in with an API like [`startTransition`](/apis/react/startTransition) or [`useDeferredValue`](/apis/react/useDeferredValue).
**React will only prevent unwanted fallbacks during non-urgent updates**. It will not delay a render if it's the result of an urgent update. You must opt in with an API like [`startTransition`](/reference/react/startTransition) or [`useDeferredValue`](/reference/react/useDeferredValue).
If your router is integrated with Suspense, it should wrap its updates into [`startTransition`](/apis/react/startTransition) automatically.
If your router is integrated with Suspense, it should wrap its updates into [`startTransition`](/reference/react/startTransition) automatically.

21
beta/src/content/reference/react/apis.md

@ -0,0 +1,21 @@
---
title: "react: APIs"
---
<Intro>
In addition to [Hooks](/reference/react) and [Components](/reference/react/components), the `react` package exports a few other APIs that are useful for defining components. This page lists all the remaining modern React APIs.
</Intro>
<InlineToc />
---
## React APIs {/*react-apis*/}
* [`createContext`](/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/reference/react/useContext)
* [`forwardRef`](/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/reference/react/useRef)
* [`lazy`](/reference/react/lazy) lets you defer loading a component's code until it's rendered for the first time.
* [`memo`](/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/reference/react/useMemo) and [`useCallback`.](/reference/react/useCallback)
* [`startTransition`](/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/reference/react/useTransition)

8
beta/src/content/apis/react/cloneElement.md → beta/src/content/reference/react/cloneElement.md

@ -47,11 +47,11 @@ console.log(clonedElement); // <Row title="Cabbage">Goodbye</Row>
#### 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.
* `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`](/reference/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.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/reference/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*/}
@ -398,7 +398,7 @@ This pattern is preferred to `cloneElement` because it is more explicit.
Another alternative to `cloneElement` is to [pass data through context.](/learn/passing-data-deeply-with-context)
For example, you can call [`createContext`](/apis/react/createContext) to define a `HighlightContext`:
For example, you can call [`createContext`](/reference/react/createContext) to define a `HighlightContext`:
```js
export const HighlightContext = createContext(false);
@ -550,7 +550,7 @@ button {
</Sandpack>
[Learn more about passing data through context.](/apis/react/useContext#passing-data-deeply-into-the-tree)
[Learn more about passing data through context.](/reference/react/useContext#passing-data-deeply-into-the-tree)
---

20
beta/src/content/reference/react/components.md

@ -0,0 +1,20 @@
---
title: "react: Components"
---
<Intro>
React exposes a few built-in components that you can use in your JSX.
</Intro>
<InlineToc />
---
## Built-in React components {/*built-in-react-components*/}
* [`<Fragment>`](/reference/react/Fragment), alternatively written as `<>...</>`, lets you group multiple JSX nodes together.
* [`<Profiler>`](/reference/react/Profiler) lets you measure rendering performance of a React tree programmatically.
* [`<Suspense>`](/reference/react/Suspense) lets you display a fallback while the child components are loading.
* [`<StrictMode>`](/reference/react/StrictMode) enables extra development-only checks that help you find bugs early.

14
beta/src/content/apis/react/createContext.md → beta/src/content/reference/react/createContext.md

@ -36,7 +36,7 @@ const ThemeContext = createContext('light');
`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:
**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)`](/reference/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.
@ -61,7 +61,7 @@ function App() {
#### 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.
* `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)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
---
@ -82,7 +82,7 @@ function Button() {
}
```
Although this older way still works, but **newly written code should read context with [`useContext()`](/apis/react/useContext) instead:**
Although this older way still works, but **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:**
```js
function Button() {
@ -94,7 +94,7 @@ function Button() {
#### 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.
* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/reference/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.
---
@ -113,7 +113,7 @@ const ThemeContext = createContext('light');
const AuthContext = createContext(null);
```
`createContext` returns a <CodeStep step={1}>context object</CodeStep>. Components can read context by passing it to [`useContext()`](/apis/react/useContext):
`createContext` returns a <CodeStep step={1}>context object</CodeStep>. Components can read context by passing it to [`useContext()`](/reference/react/useContext):
```js [[1, 2, "ThemeContext"], [1, 7, "AuthContext"]]
function Button() {
@ -150,7 +150,7 @@ function App() {
Now the `Page` component and any components inside it, no matter how deep, will "see" the passed context values. If the passed context values change, React will re-render the components reading the context as well.
[Read more about reading and providing context and see examples.](/apis/react/useContext)
[Read more about reading and providing context and see examples.](/reference/react/useContext)
---
@ -211,5 +211,5 @@ const ThemeContext = createContext('light');
This value never changes. React only uses this value as a fallback if it can't find a matching provider above.
To make context change over time, [add state and wrap components in a context provider.](/apis/react/useContext#updating-data-passed-via-context)
To make context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context)

4
beta/src/content/apis/react/createElement.md → beta/src/content/reference/react/createElement.md

@ -38,11 +38,11 @@ function Greeting({ name }) {
#### 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)).
* `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`](/reference/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.
* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
#### Returns {/*returns*/}

4
beta/src/content/apis/react/createFactory.md → beta/src/content/reference/react/createFactory.md

@ -54,7 +54,7 @@ export default function App() {
#### 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)).
* `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`](/reference/react/Fragment)).
#### Returns {/*returns*/}
@ -144,7 +144,7 @@ This lets you keep all of your code unchanged except the imports.
### Replacing `createFactory` with `createElement` {/*replacing-createfactory-with-createelement*/}
If you have a few `createFactory` calls that you don't mind porting manually, and you don't want to use JSX, you can replace every call a factory function with a [`createElement`](/apis/react/createElement) call. For example, you can replace this code:
If you have a few `createFactory` calls that you don't mind porting manually, and you don't want to use JSX, you can replace every call a factory function with a [`createElement`](/reference/react/createElement) call. For example, you can replace this code:
```js {1,3,6}
import { createFactory } from 'react';

16
beta/src/content/apis/react/createRef.md → beta/src/content/reference/react/createRef.md

@ -4,7 +4,7 @@ title: createRef
<Pitfall>
`createRef` is mostly used for [class components.](/apis/react/Component) Function components typically rely on [`useRef`](/apis/react/useRef) instead.
`createRef` is mostly used for [class components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead.
</Pitfall>
@ -29,7 +29,7 @@ class MyInput extends Component {
### `createRef()` {/*createref*/}
Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [class component.](/apis/react/Component)
Call `createRef` to declare a [ref](/learn/referencing-values-with-refs) inside a [class component.](/reference/react/Component)
```js
import { createRef, Component } from 'react';
@ -42,7 +42,7 @@ class MyComponent extends Component {
<Pitfall>
`createRef` is mostly used for [class components.](/apis/react/Component) Function components typically rely on [`useRef`](/apis/react/useRef) instead.
`createRef` is mostly used for [class components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead.
</Pitfall>
@ -59,7 +59,7 @@ class MyComponent extends Component {
#### 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.
* In a function component, you probably want [`useRef`](/reference/react/useRef) instead which always returns the same object.
* `const ref = useRef()` is equivalent to `const [ref, _] = useState(() => createRef(null))`.
---
@ -68,7 +68,7 @@ class MyComponent extends Component {
### Declaring a ref in a class component {/*declaring-a-ref-in-a-class-component*/}
To declare a ref inside a [class component,](/apis/react/Component) call `createRef` and assign its result to a class field:
To declare a ref inside a [class component,](/reference/react/Component) call `createRef` and assign its result to a class field:
```js {4}
import { Component, createRef } from 'react';
@ -111,7 +111,7 @@ export default class Form extends Component {
<Pitfall>
`createRef` is mostly used for [class components.](/apis/react/Component) Function components typically rely on [`useRef`](/apis/react/useRef) instead.
`createRef` is mostly used for [class components.](/reference/react/Component) Function components typically rely on [`useRef`](/reference/react/useRef) instead.
</Pitfall>
@ -121,7 +121,7 @@ export default class Form extends Component {
### Migrating from a class with `createRef` to a function with `useRef` {/*migrating-from-a-class-with-createref-to-a-function-with-useref*/}
We recommend to use function components instead of [class components](/apis/react/Component) in the new code. If you have some existing class components using `createRef`, here is how you can convert them. This is the original code:
We recommend to use function components instead of [class components](/reference/react/Component) in the new code. If you have some existing class components using `createRef`, here is how you can convert them. This is the original code:
<Sandpack>
@ -150,7 +150,7 @@ export default class Form extends Component {
</Sandpack>
When you [convert this component from a class to a function,](/apis/react/Component#alternatives) replace calls to `createRef` with calls to [`useRef`:](/apis/react/useRef)
When you [convert this component from a class to a function,](/reference/react/Component#alternatives) replace calls to `createRef` with calls to [`useRef`:](/reference/react/useRef)
<Sandpack>

8
beta/src/content/apis/react/forwardRef.md → beta/src/content/reference/react/forwardRef.md

@ -65,7 +65,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
* `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)
* `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`.](/reference/react/useImperativeHandle)
#### Returns {/*render-returns*/}
@ -130,7 +130,7 @@ function Form() {
}
```
This `Form` component [passes a ref](/apis/useref#manipulating-the-dom-with-a-ref) to `MyInput`. The `MyInput` component *forwards* that ref to the `<input>` browser tag. As a result, the `Form` component can access that `<input>` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it.
This `Form` component [passes a ref](/reference/useref#manipulating-the-dom-with-a-ref) to `MyInput`. The `MyInput` component *forwards* that ref to the `<input>` browser tag. As a result, the `Form` component can access that `<input>` DOM node and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it.
Keep in mind that by exposing a ref to the DOM node inside your component, you're making it harder to change your component's internals later. You will typically expose DOM nodes from reusable low-level components like buttons or text inputs, but you won't do it for application-level components like an avatar or a comment.
@ -380,7 +380,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
});
```
Then pass the `ref` you received to [`useImperativeHandle`](/apis/react/useImperativeHandle) and specify the value you want to expose to the `ref`:
Then pass the `ref` you received to [`useImperativeHandle`](/reference/react/useImperativeHandle) and specify the value you want to expose to the `ref`:
```js {6-15}
import { forwardRef, useRef, useImperativeHandle } from 'react';
@ -462,7 +462,7 @@ input {
</Sandpack>
[Read more about using imperative handles.](/apis/react/useImperativeHandle)
[Read more about using imperative handles.](/reference/react/useImperativeHandle)
<Pitfall>

40
beta/src/content/apis/react/index.md → beta/src/content/reference/react/index.md

@ -18,8 +18,8 @@ title: "react: Hooks"
To add state to a component, use one of these Hooks:
* [`useState`](/apis/react/useState) declares a state variable that you can update directly.
* [`useReducer`](/apis/react/useReducer) declares a state variable with the update logic inside a [reducer function.](/learn/extracting-state-logic-into-a-reducer)
* [`useState`](/reference/react/useState) declares a state variable that you can update directly.
* [`useReducer`](/reference/react/useReducer) declares a state variable with the update logic inside a [reducer function.](/learn/extracting-state-logic-into-a-reducer)
```js
function ImageGallery() {
@ -27,7 +27,7 @@ function ImageGallery() {
// ...
```
[See the `useState` page for more examples.](/apis/react/useState)
[See the `useState` page for more examples.](/reference/react/useState)
---
@ -35,7 +35,7 @@ function ImageGallery() {
[Context](/learn/passing-data-deeply-with-context) lets a component receive information from distant parents without [passing it as props.](/learn/passing-props-to-a-component) For example, your app's top-level component can pass the current UI theme to all components below, no matter how deep.
* [`useContext`](/apis/react/useContext) reads and subscribes to a context.
* [`useContext`](/reference/react/useContext) reads and subscribes to a context.
```js
function Button() {
@ -43,7 +43,7 @@ function Button() {
// ...
```
[See the `useContext` page for more examples.](/apis/react/useContext)
[See the `useContext` page for more examples.](/reference/react/useContext)
---
@ -51,8 +51,8 @@ function Button() {
[Refs](/learn/referencing-values-with-refs) let a component hold some information that isn't used for rendering, like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an "escape hatch" from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
* [`useRef`](/apis/react/useRef) declares a ref. You can hold any value in it, but most often it's used to hold a DOM node.
* [`useImperativeHandle`](/apis/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used.
* [`useRef`](/reference/react/useRef) declares a ref. You can hold any value in it, but most often it's used to hold a DOM node.
* [`useImperativeHandle`](/reference/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used.
```js
function Form() {
@ -60,7 +60,7 @@ function Form() {
// ...
```
[See the `useRef` page for more examples.](/apis/react/useRef)
[See the `useRef` page for more examples.](/reference/react/useRef)
---
@ -68,7 +68,7 @@ function Form() {
[Effects](/learn/synchronizing-with-effects) let a component connect to and synchronize with external systems. This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and in general any non-React code.
* [`useEffect`](/apis/react/useEffect) connects a component to an external system.
* [`useEffect`](/reference/react/useEffect) connects a component to an external system.
```js
function ChatRoom({ roomId }) {
@ -80,14 +80,14 @@ function ChatRoom({ roomId }) {
// ...
```
[See the `useEffect` page for more examples.](/apis/react/useEffect)
[See the `useEffect` page for more examples.](/reference/react/useEffect)
Effects are an "escape hatch" from the React paradigm. Don't use Effects to orchestrate the data flow of your application. If you're not interacting with an external system, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
There are two variations of `useEffect` with differences in timing:
* [`useLayoutEffect`](/apis/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here.
* [`useInsertionEffect`](/apis/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
* [`useLayoutEffect`](/reference/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here.
* [`useInsertionEffect`](/reference/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
They are rarely used.
@ -99,8 +99,8 @@ A common way to optimize re-rendering performance is to skip unnecessary work. F
To skip calculations and unnecessary re-rendering, use one of these Hooks:
- [`useMemo`](/apis/react/useMemo) lets you cache the result of an expensive calculation.
- [`useCallback`](/apis/react/useCallback) lets you cache a function definition before passing it down to an optimized component.
- [`useMemo`](/reference/react/useMemo) lets you cache the result of an expensive calculation.
- [`useCallback`](/reference/react/useCallback) lets you cache a function definition before passing it down to an optimized component.
```js
function TodoList({ todos, tab, theme }) {
@ -109,14 +109,14 @@ function TodoList({ todos, tab, theme }) {
}
```
[See the `useMemo` page for more examples.](/apis/react/useMemo)
[See the `useMemo` page for more examples.](/reference/react/useMemo)
Sometimes, you can't skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don't need to block the user interface (like updating a chart).
To prioritize rendering, use one of these Hooks:
- [`useTransition`](/apis/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it.
- [`useDeferredValue`](/apis/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first.
- [`useTransition`](/reference/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it.
- [`useDeferredValue`](/reference/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first.
---
@ -124,6 +124,6 @@ To prioritize rendering, use one of these Hooks:
These Hooks are mostly useful to library authors and aren't commonly used in the application code.
- [`useDebugValue`](/apis/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook.
- [`useId`](/apis/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs.
- [`useSyncExternalStore`](/apis/react/useSyncExternalStore) lets a component subscribe to an external store.
- [`useDebugValue`](/reference/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook.
- [`useId`](/reference/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs.
- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) lets a component subscribe to an external store.

8
beta/src/content/apis/react/isValidElement.md → beta/src/content/reference/react/isValidElement.md

@ -47,7 +47,7 @@ console.log(isValidElement({ age: 42 })); // 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.
* **Only [JSX tags](/learn/writing-markup-with-jsx) and objects returned by [`createElement`](/reference/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`](/reference/react-dom/createPortal) are also *not* considered to be React elements.
---
@ -60,7 +60,7 @@ Call `isValidElement` to check if some value is a *React element.*
React elements are:
- Values produced by writing a [JSX tag](/learn/writing-markup-with-jsx)
- Values produced by calling [`createElement`](/apis/react/createElement)
- Values produced by calling [`createElement`](/reference/react/createElement)
For React elements, `isValidElement` returns `true`:
@ -90,7 +90,7 @@ console.log(isValidElement([<div />, <div />])); // false
console.log(isValidElement(MyComponent)); // false
```
It is very uncommon to need `isValidElement`. It's mostly useful if you're calling another API that *only* accepts elements (like [`cloneElement`](/apis/react/cloneElement) does) and you want to avoid an error when your argument is not a React element.
It is very uncommon to need `isValidElement`. It's mostly useful if you're calling another API that *only* accepts elements (like [`cloneElement`](/reference/react/cloneElement) does) and you want to avoid an error when your argument is not a React element.
Unless you have some very specific reason to add an `isValidElement` check, you probably don't need it.
@ -109,7 +109,7 @@ function MyComponent() {
A React node can be:
- A React element created like `<div />` or `createElement('div')`
- A portal created with [`createPortal`](/apis/react-dom/createPortal)
- A portal created with [`createPortal`](/reference/react-dom/createPortal)
- A string
- A number
- `true`, `false`, `null`, or `undefined` (which are not displayed)

8
beta/src/content/apis/react/lazy.md → beta/src/content/reference/react/lazy.md

@ -32,7 +32,7 @@ const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
#### 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.
`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>`](/reference/react/Suspense) to display a loading indicator while it's loading.
---
@ -44,7 +44,7 @@ const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
#### 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.
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`](/reference/react/memo), or a [`forwardRef`](/reference/react/forwardRef) component.
---
@ -68,7 +68,7 @@ const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
This code relies on [dynamic `import()`,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) which might require support from your bundler or framework.
Now that your component's code loads on demand, you also need to specify what should be displayed while it is loading. You can do this by wrapping the lazy component or any of its parents into a [`<Suspense>`](/apis/react/Suspense) boundary:
Now that your component's code loads on demand, you also need to specify what should be displayed while it is loading. You can do this by wrapping the lazy component or any of its parents into a [`<Suspense>`](/reference/react/Suspense) boundary:
```js {1,4}
<Suspense fallback={<Loading />}>
@ -173,7 +173,7 @@ body {
This demo loads with an artificial delay. The next time you untick and tick the checkbox, `Preview` will be cached, so there will be no loading state displayed. To see the loading state again, click "Reset" on the sandbox.
[Learn more about managing loading states with Suspense.](/apis/react/Suspense)
[Learn more about managing loading states with Suspense.](/reference/react/Suspense)
---

34
beta/src/content/reference/react/legacy.md

@ -0,0 +1,34 @@
---
title: "react: Legacy APIs"
---
<Intro>
These APIs are exported from the `react` package, but they are not recommended for use in the newly written code. See the linked individual API pages for the suggested alternatives.
</Intro>
---
## Legacy React APIs {/*legacy-react-apis*/}
* [`Children`](/reference/react/Children) lets you manipulate and transform the JSX received as the `children` prop. [See alternatives.](/reference/react/Children#alternatives)
* [`cloneElement`](/reference/react/cloneElement) lets you create a React element using another element as a starting point. [See alternatives.](/reference/react/cloneElement#alternatives)
* [`Component`](/reference/react/Component) lets you define a React component as a JavaScript class. [See alternatives.](/reference/react/Component#alternatives)
* [`createElement`](/reference/react/createElement) lets you create a React element. Typically, you'll use JSX instead.
* [`createRef`](/reference/react/createRef) creates a ref object which can contain arbitrary value. [See alternatives.](/reference/react/createRef#alternatives)
* [`isValidElement`](/reference/react/isValidElement) checks whether a value is a React element. Typically used with [`cloneElement`.](/reference/react/cloneElement)
* [`PureComponent`](/reference/react/PureComponent) is similar to [`Component`,](/reference/react/Component) but it skip re-renders with same props. [See alternatives.](/reference/react/PureComponent#alternatives)
---
## Deprecated React APIs {/*deprecated-react-apis*/}
<Deprecated>
These APIs will be removed in a future major version of React.
</Deprecated>
* [`createFactory`](/reference/react/createFactory) lets you create a function that produces React elements of a certain type.

8
beta/src/content/apis/react/memo.md → beta/src/content/reference/react/memo.md

@ -34,7 +34,7 @@ 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.
* `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`](/reference/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`.
@ -114,7 +114,7 @@ label {
If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful.
Optimizing with `memo` is only valuable when your component re-renders often with the same exact props, and its re-rendering logic is expensive. If there is no perceptible lag when your component re-renders, `memo` is unnecessary. Keep in mind that `memo` is completely useless if the props passed to your component are *always different,* such as if you pass an object or a plain function defined during rendering. This is why you will often need [`useMemo`](/apis/react/useMemo#skipping-re-rendering-of-components) and [`useCallback`](/apis/react/useCallback#skipping-re-rendering-of-components) together with `memo`.
Optimizing with `memo` is only valuable when your component re-renders often with the same exact props, and its re-rendering logic is expensive. If there is no perceptible lag when your component re-renders, `memo` is unnecessary. Keep in mind that `memo` is completely useless if the props passed to your component are *always different,* such as if you pass an object or a plain function defined during rendering. This is why you will often need [`useMemo`](/reference/react/useMemo#skipping-re-rendering-of-components) and [`useCallback`](/reference/react/useCallback#skipping-re-rendering-of-components) together with `memo`.
There is no benefit to wrapping a component in `memo` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value that's "always new" is enough to break memoization for an entire component.
@ -272,7 +272,7 @@ To make your component re-render only when a _part_ of some context changes, spl
When you use `memo`, your component re-renders whenever any prop is not *shallowly equal* to what it was previously. This means that React compares every prop in your component with the previous value of that prop using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Note that `Object.is(3, 3)` is `true`, but `Object.is({}, {})` is `false`.
To get the most out of `memo`, minimize the times that the props change. For example, if the prop is an object, prevent the parent component from re-creating that object every time by using [`useMemo`:](/apis/react/useMemo)
To get the most out of `memo`, minimize the times that the props change. For example, if the prop is an object, prevent the parent component from re-creating that object every time by using [`useMemo`:](/reference/react/useMemo)
```js {5-8}
function Page() {
@ -319,7 +319,7 @@ const CallToAction = memo(function CallToAction({ hasGroups }) {
});
```
When you need to pass a function to memoized component, either declare it outside your component so that it never changes, or [`useCallback`](/apis/react/useCallback#skipping-re-rendering-of-components) to cache its definition between re-renders.
When you need to pass a function to memoized component, either declare it outside your component so that it never changes, or [`useCallback`](/reference/react/useCallback#skipping-re-rendering-of-components) to cache its definition between re-renders.
---

10
beta/src/content/apis/react/startTransition.md → beta/src/content/reference/react/startTransition.md

@ -39,7 +39,7 @@ function TabContainer() {
#### 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)
* `scope`: A function that updates some state by calling one or more [`set` functions.](/reference/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](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](/reference/react/useTransition#preventing-unwanted-loading-indicators)
#### Returns {/*returns*/}
@ -47,9 +47,9 @@ function TabContainer() {
#### 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.
* `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`](/reference/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.
* 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`](/reference/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.
@ -88,8 +88,8 @@ With a transition, your UI stays responsive in the middle of a re-render. For ex
<Note>
`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` is very similar to [`useTransition`](/reference/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.
[Learn about transitions and see examples on the `useTransition` page.](/apis/react/useTransition)
[Learn about transitions and see examples on the `useTransition` page.](/reference/react/useTransition)
</Note>

32
beta/src/content/apis/react/useCallback.md → beta/src/content/reference/react/useCallback.md

@ -51,7 +51,7 @@ During subsequent renders, it will either return an already stored `fn` functio
#### 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.
* 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](/reference/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead) or a [ref](/reference/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
@ -103,7 +103,7 @@ function ProductPage({ productId, referrer, theme }) {
You've noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `<ShippingForm />` from your JSX, it feels fast. This tells you that it's worth trying to optimize the `ShippingForm` component.
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `ProductPage` re-renders with a different `theme`, the `ShippingForm` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you've verified that a re-render is slow, you can tell `ShippingForm` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/apis/react/memo)
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `ProductPage` re-renders with a different `theme`, the `ShippingForm` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you've verified that a re-render is slow, you can tell `ShippingForm` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/reference/react/memo)
```js {3,5}
import { memo } from 'react';
@ -134,7 +134,7 @@ function ProductPage({ productId, referrer, theme }) {
}
```
**In JavaScript, a `function () {}` or `() => {}` always creates a _different_ function,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `ShippingForm` props will never be the same, and your [`memo`](/apis/react/memo) optimization won't work. This is where `useCallback` comes in handy:
**In JavaScript, a `function () {}` or `() => {}` always creates a _different_ function,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `ShippingForm` props will never be the same, and your [`memo`](/reference/react/memo) optimization won't work. This is where `useCallback` comes in handy:
```js {2,3,8,12-13}
function ProductPage({ productId, referrer, theme }) {
@ -155,7 +155,7 @@ function ProductPage({ productId, referrer, theme }) {
}
```
**By wrapping `handleSubmit` in `useCallback`, you ensure that it's the *same* function between the re-renders** (until dependencies change). You don't *have to* wrap a function in `useCallback` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](/apis/react/memo) and this lets it skip re-rendering. There are a few other reasons you might need `useCallback` which are described further on this page.
**By wrapping `handleSubmit` in `useCallback`, you ensure that it's the *same* function between the re-renders** (until dependencies change). You don't *have to* wrap a function in `useCallback` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](/reference/react/memo) and this lets it skip re-rendering. There are a few other reasons you might need `useCallback` which are described further on this page.
<Note>
@ -167,7 +167,7 @@ function ProductPage({ productId, referrer, theme }) {
#### How is useCallback related to useMemo? {/*how-is-usecallback-related-to-usememo*/}
You will often see [`useMemo`](/apis/react/useMemo) alongside `useCallback`. They are both useful when you're trying to optimize a child component. They let you [memoize](https://en.wikipedia.org/wiki/Memoization) (or, in other words, cache) something you're passing down:
You will often see [`useMemo`](/reference/react/useMemo) alongside `useCallback`. They are both useful when you're trying to optimize a child component. They let you [memoize](https://en.wikipedia.org/wiki/Memoization) (or, in other words, cache) something you're passing down:
```js {6-8,10-15,19}
import { useMemo, useCallback } from 'react';
@ -196,10 +196,10 @@ function ProductPage({ productId, referrer }) {
The difference is in *what* they're letting you cache:
* **[`useMemo`](/apis/react/useMemo) caches the *result* of calling your function.** In this example, it caches the result of calling `computeRequirements(product)` so that it doesn't change unless `product` has changed. This lets you pass the `requirements` object down without unnecessarily re-rendering `ShippingForm`. When necessary, React will call the function you've passed during rendering to calculate the result.
* **[`useMemo`](/reference/react/useMemo) caches the *result* of calling your function.** In this example, it caches the result of calling `computeRequirements(product)` so that it doesn't change unless `product` has changed. This lets you pass the `requirements` object down without unnecessarily re-rendering `ShippingForm`. When necessary, React will call the function you've passed during rendering to calculate the result.
* **`useCallback` caches *the function itself.*** Unlike `useMemo`, it does not call the function you provide. Instead, it caches the function you provided so that `handleSubmit` *itself* doesn't change unless `productId` or `referrer` has changed. This lets you pass the `handleSubmit` function down without unnecessarily re-rendering `ShippingForm`. Your code won't be called until the user submits the form.
If you're already familiar with [`useMemo`,](/apis/react/useMemo) you might find it helpful to think of `useCallback` as this:
If you're already familiar with [`useMemo`,](/reference/react/useMemo) you might find it helpful to think of `useCallback` as this:
```js
// Simplified implementation (inside React)
@ -208,7 +208,7 @@ function useCallback(fn, dependencies) {
}
```
[Read more about the difference between `useMemo` and `useCallback`.](/apis/react/useMemo#memoizing-a-function)
[Read more about the difference between `useMemo` and `useCallback`.](/reference/react/useMemo#memoizing-a-function)
</DeepDive>
@ -220,8 +220,8 @@ If your app is like this site, and most interactions are coarse (like replacing
Caching a function with `useCallback` is only valuable in a few cases:
- You pass it as a prop to a component wrapped in [`memo`.](/apis/react/memo) You want to skip re-rendering if the value hasn't changed. Memoization lets your component re-render only when dependencies aren't the same.
- The function you're passing is later used as a dependency of some Hook. For example, another function wrapped in `useCallback` depends on it, or you depend on this function from [`useEffect.`](/apis/react/useEffect)
- You pass it as a prop to a component wrapped in [`memo`.](/reference/react/memo) You want to skip re-rendering if the value hasn't changed. Memoization lets your component re-render only when dependencies aren't the same.
- The function you're passing is later used as a dependency of some Hook. For example, another function wrapped in `useCallback` depends on it, or you depend on this function from [`useEffect.`](/reference/react/useEffect)
There is no benefit to wrapping a function in `useCallback` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value that's "always new" is enough to break memoization for an entire component.
@ -247,7 +247,7 @@ In this example, the `ShippingForm` component is **artificially slowed down** so
Incrementing the counter feels slow because it forces the slowed down `ShippingForm` to re-render. That's expected because the counter has changed, and so you need to reflect the user's new choice on the screen.
Next, try toggling the theme. **Thanks to `useCallback` together with [`memo`](/apis/react/memo), it’s fast despite the artificial slowdown!** `ShippingForm` skipped re-rendering because the `handleSubmit` function has not changed. The `handleSubmit` function has not changed because both `productId` and `referral` (your `useCallback` dependencies) haven't changed since last render.
Next, try toggling the theme. **Thanks to `useCallback` together with [`memo`](/reference/react/memo), it’s fast despite the artificial slowdown!** `ShippingForm` skipped re-rendering because the `handleSubmit` function has not changed. The `handleSubmit` function has not changed because both `productId` and `referral` (your `useCallback` dependencies) haven't changed since last render.
<Sandpack>
@ -677,7 +677,7 @@ function TodoList() {
// ...
```
You'll usually want your memoized functions to have as few dependencies as possible. When you read some state only to calculate the next state, you can remove that dependency by passing an [updater function](/apis/react/useState#updating-state-based-on-the-previous-state) instead:
You'll usually want your memoized functions to have as few dependencies as possible. When you read some state only to calculate the next state, you can remove that dependency by passing an [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) instead:
```js {6,7}
function TodoList() {
@ -690,7 +690,7 @@ function TodoList() {
// ...
```
Here, instead of making `todos` a dependency of your function and reading it there, you pass an instruction about *how* to update the state (`todos => [...todos, newTodo]`) to React. [Read more about updater functions.](/apis/react/useState#updating-state-based-on-the-previous-state)
Here, instead of making `todos` a dependency of your function and reading it there, you pass an instruction about *how* to update the state (`todos => [...todos, newTodo]`) to React. [Read more about updater functions.](/reference/react/useState#updating-state-based-on-the-previous-state)
---
@ -854,13 +854,13 @@ Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...
```
When you find which dependency is breaking memoization, either find a way to remove it, or [memoize it as well.](/apis/react/useMemo#memoizing-a-dependency-of-another-hook)
When you find which dependency is breaking memoization, either find a way to remove it, or [memoize it as well.](/reference/react/useMemo#memoizing-a-dependency-of-another-hook)
---
### I need to call `useCallback` for each list item in a loop, but it's not allowed {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/}
Suppose the `Chart` component is wrapped in [`memo`](/apis/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useCallback` in a loop:
Suppose the `Chart` component is wrapped in [`memo`](/reference/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useCallback` in a loop:
```js {5-14}
function ReportList({ items }) {
@ -910,7 +910,7 @@ function Report({ item }) {
}
```
Alternatively, you could remove `useCallback` in the last snippet and instead wrap `Report` itself in [`memo`.](/apis/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
Alternatively, you could remove `useCallback` in the last snippet and instead wrap `Report` itself in [`memo`.](/reference/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```js {5,6-8,15}
function ReportList({ items }) {

16
beta/src/content/apis/react/useContext.md → beta/src/content/reference/react/useContext.md

@ -34,16 +34,16 @@ function MyComponent() {
#### 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.
* `SomeContext`: The context that you've previously created with [`createContext`](/reference/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.
`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`](/reference/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.
* 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`](/reference/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.
---
@ -177,7 +177,7 @@ function Button({ children }) {
### Updating data passed via context {/*updating-data-passed-via-context*/}
Often, you'll want the context to change over time. To update context, you need to combine it with [state.](/apis/react/useState) Declare a state variable in the parent component, and pass the current state down as the <CodeStep step={2}>context value</CodeStep> to the provider.
Often, you'll want the context to change over time. To update context, you need to combine it with [state.](/reference/react/useState) Declare a state variable in the parent component, and pass the current state down as the <CodeStep step={2}>context value</CodeStep> to the provider.
```js {2} [[1, 4, "ThemeContext"], [2, 4, "theme"], [1, 11, "ThemeContext"]]
function MyPage() {
@ -739,7 +739,7 @@ label {
#### Scaling up with context and a reducer {/*scaling-up-with-context-and-a-reducer*/}
In larger apps, it is common to combine context with a [reducer](/apis/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate contexts.
In larger apps, it is common to combine context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate contexts.
Read a [full walkthrough](/learn/scaling-up-with-reducer-and-context) of this example.
@ -949,7 +949,7 @@ ul, li { margin: 0; padding: 0; }
### Specifying a fallback default value {/*specifying-a-fallback-default-value*/}
If React can't find any providers of that particular <CodeStep step={1}>context</CodeStep> in the parent tree, the context value returned by `useContext()` will be equal to the <CodeStep step={3}>default value</CodeStep> that you specified when you [created that context](/apis/react/createContext):
If React can't find any providers of that particular <CodeStep step={1}>context</CodeStep> in the parent tree, the context value returned by `useContext()` will be equal to the <CodeStep step={3}>default value</CodeStep> that you specified when you [created that context](/reference/react/createContext):
```js [[1, 1, "ThemeContext"], [3, 1, "null"]]
const ThemeContext = createContext(null);
@ -1311,7 +1311,7 @@ function MyApp() {
Here, the <CodeStep step={2}>context value</CodeStep> is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`.
In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](/apis/react/useCallback) and wrap the object creation into [`useMemo`](/apis/react/useMemo). This is a performance optimization:
In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](/reference/react/useCallback) and wrap the object creation into [`useMemo`](/reference/react/useMemo). This is a performance optimization:
```js {6,9,11,14,17}
import { useCallback, useMemo } from 'react';
@ -1337,7 +1337,7 @@ function MyApp() {
}
```
As a result of this change, even if `MyApp` needs to re-render, the components calling `useContext(AuthProvider)` won't need to re-render unless `currentUser` has changed. Read more about [`useMemo`](/apis/react/useMemo#skipping-re-rendering-of-components) and [`useCallback`.](/apis/react/useCallback#skipping-re-rendering-of-components)
As a result of this change, even if `MyApp` needs to re-render, the components calling `useContext(AuthProvider)` won't need to re-render unless `currentUser` has changed. Read more about [`useMemo`](/reference/react/useMemo#skipping-re-rendering-of-components) and [`useCallback`.](/reference/react/useCallback#skipping-re-rendering-of-components)
---

0
beta/src/content/apis/react/useDebugValue.md → beta/src/content/reference/react/useDebugValue.md

12
beta/src/content/apis/react/useDeferredValue.md → beta/src/content/reference/react/useDeferredValue.md

@ -48,7 +48,7 @@ During the initial render, the returned deferred value will be the same as the v
- 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` is integrated with [`<Suspense>`.](/reference/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.
@ -85,14 +85,14 @@ During updates, the <CodeStep step={2}>deferred value</CodeStep> will "lag behin
This example assumes you use one of Suspense-enabled data sources:
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/advanced-features/react-18)
- Lazy-loading component code with [`lazy`](/apis/react/lazy)
- Lazy-loading component code with [`lazy`](/reference/react/lazy)
[Learn more about Suspense and its limitations.](/apis/react/Suspense)
[Learn more about Suspense and its limitations.](/reference/react/Suspense)
</Note>
In this example, the `SearchResults` component [suspends](/apis/react/Suspense#displaying-a-fallback-while-content-is-loading) while fetching the search results. Try typing `"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"` will get replaced by the loading fallback.
In this example, the `SearchResults` component [suspends](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading) while fetching the search results. Try typing `"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"` will get replaced by the loading fallback.
<Sandpack>
@ -748,7 +748,7 @@ function App() {
}
```
First, optimize `SlowList` to skip re-rendering when its props are the same. To do this, [wrap it in `memo`:](/apis/react/memo#skipping-re-rendering-when-props-are-unchanged)
First, optimize `SlowList` to skip re-rendering when its props are the same. To do this, [wrap it in `memo`:](/reference/react/memo#skipping-re-rendering-when-props-are-unchanged)
```js {1,3}
const SlowList = memo(function SlowList({ text }) {
@ -934,7 +934,7 @@ export default SlowList;
<Pitfall>
This optimization requires `SlowList` to be wrapped in [`memo`.](/apis/react/memo) This is because whenever the `text` changes, React needs to be able to re-render the parent component quickly. During that re-render, `deferredText` still has its previous value, so `SlowList` is able to skip re-rendering (its props have not changed). Without [`memo`,](/apis/react/memo) it would have to re-render anyway, defeating the point of the optimization.
This optimization requires `SlowList` to be wrapped in [`memo`.](/reference/react/memo) This is because whenever the `text` changes, React needs to be able to re-render the parent component quickly. During that re-render, `deferredText` still has its previous value, so `SlowList` is able to skip re-rendering (its props have not changed). Without [`memo`,](/reference/react/memo) it would have to re-render anyway, defeating the point of the optimization.
</Pitfall>

18
beta/src/content/apis/react/useEffect.md → beta/src/content/reference/react/useEffect.md

@ -62,9 +62,9 @@ function ChatRoom({ roomId }) {
* 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)
* 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`.](/reference/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)
* 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`.](/reference/react/useLayoutEffect)
* Effects **only run on the client.** They don't run during server rendering.
@ -1435,7 +1435,7 @@ function Counter() {
Since `count` is a reactive value, it must be specified in the list of dependencies. However, that causes the Effect to cleanup and setup again every time the `count` changes. This is not ideal.
To fix this, [pass the `c => c + 1` state updater](/apis/react/useState#updating-state-based-on-the-previous-state) to `setCount`:
To fix this, [pass the `c => c + 1` state updater](/reference/react/useState#updating-state-based-on-the-previous-state) to `setCount`:
<Sandpack>
@ -1707,7 +1707,7 @@ function Page({ url, shoppingCart }) {
}
```
**What if you want to log a new page visit after every `url` change, but *not* if only the `shoppingCart` changes?** You can't exclude `shoppingCart` from dependencies without breaking the [reactivity rules.](#specifying-reactive-dependencies) However, you can express that you *don't want* a piece of code to "react" to changes even though it is called from inside an Effect. [Declare an *Effect Event*](/learn/separating-events-from-effects#declaring-an-effect-event) with the [`useEffectEvent`](/apis/react/useEffectEvent) Hook, and move the code that reads `shoppingCart` inside of it:
**What if you want to log a new page visit after every `url` change, but *not* if only the `shoppingCart` changes?** You can't exclude `shoppingCart` from dependencies without breaking the [reactivity rules.](#specifying-reactive-dependencies) However, you can express that you *don't want* a piece of code to "react" to changes even though it is called from inside an Effect. [Declare an *Effect Event*](/learn/separating-events-from-effects#declaring-an-effect-event) with the [`useEffectEvent`](/reference/react/useEffectEvent) Hook, and move the code that reads `shoppingCart` inside of it:
```js {2-4,7,8}
function Page({ url, shoppingCart }) {
@ -1731,7 +1731,7 @@ function Page({ url, shoppingCart }) {
### Displaying different content on the server and the client {/*displaying-different-content-on-the-server-and-the-client*/}
If your app uses server rendering (either [directly](/apis/react-dom/server) or via a [framework](/learn/start-a-new-react-project#building-with-a-full-featured-framework)), your component will render in two different environments. On the server, it will render to produce the initial HTML. On the client, React will run the rendering code again so that it can attach your event handlers to that HTML. This is why, for [hydration](/apis/react-dom/client/hydrateRoot#hydrating-server-rendered-html) to work, your initial render output must be identical on the client and the server.
If your app uses server rendering (either [directly](/reference/react-dom/server) or via a [framework](/learn/start-a-new-react-project#building-with-a-full-featured-framework)), your component will render in two different environments. On the server, it will render to produce the initial HTML. On the client, React will run the rendering code again so that it can attach your event handlers to that HTML. This is why, for [hydration](/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) to work, your initial render output must be identical on the client and the server.
In rare cases, you might need to display different content on the client. For example, if your app reads some data from [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), it can't possibly do that on the server. Here is how you would typically implement this:
@ -1806,7 +1806,7 @@ When you find the dependency that is different on every re-render, you can usual
- [Removing unnecessary function dependencies](#removing-unnecessary-function-dependencies)
- [Reading the latest props and state from an Effect](#reading-the-latest-props-and-state-from-an-effect)
As a last resort (if these methods didn't help), wrap its creation with [`useMemo`](/apis/react/useMemo#memoizing-a-dependency-of-another-hook) or [`useCallback`](/apis/react/useCallback#preventing-an-effect-from-firing-too-often) (for functions).
As a last resort (if these methods didn't help), wrap its creation with [`useMemo`](/reference/react/useMemo#memoizing-a-dependency-of-another-hook) or [`useCallback`](/reference/react/useCallback#preventing-an-effect-from-firing-too-often) (for functions).
---
@ -1821,9 +1821,9 @@ Before you start fixing the problem, ask yourself whether your Effect is connect
If there is no external system, consider whether [removing the Effect altogether](/learn/you-might-not-need-an-effect) would simplify your logic.
If you're genuinely synchronizing with some external system, think about why and under what conditions your Effect should update the state. Has something changed that affects your component's visual output? If you need to keep track of some data that isn't used by rendering, a [ref](/apis/react/useRef#referencing-a-value-with-a-ref) (which doesn't trigger re-renders) might be more appropriate. Verify your Effect doesn't update the state (and trigger re-renders) more than needed.
If you're genuinely synchronizing with some external system, think about why and under what conditions your Effect should update the state. Has something changed that affects your component's visual output? If you need to keep track of some data that isn't used by rendering, a [ref](/reference/react/useRef#referencing-a-value-with-a-ref) (which doesn't trigger re-renders) might be more appropriate. Verify your Effect doesn't update the state (and trigger re-renders) more than needed.
Finally, if your Effect is updating the state at the right time, but there is still a loop, it's because that state update leads to one of your Effect's dependencies changing. [Read how to debug and resolve dependency changes.](/apis/react/useEffect#my-effect-runs-after-every-re-render)
Finally, if your Effect is updating the state at the right time, but there is still a loop, it's because that state update leads to one of your Effect's dependencies changing. [Read how to debug and resolve dependency changes.](/reference/react/useEffect#my-effect-runs-after-every-re-render)
---
@ -1860,4 +1860,4 @@ Your cleanup logic should be "symmetrical" to the setup logic, and should stop o
### My Effect does something visual, and I see a flicker before it runs {/*my-effect-does-something-visual-and-i-see-a-flicker-before-it-runs*/}
If your Effect must block the browser from [painting the screen,](/learn/render-and-commit#epilogue-browser-paint) replace `useEffect` with [`useLayoutEffect`](/apis/react/useLayoutEffect). Note that **this shouldn't be needed for the vast majority of Effects.** You'll only need this if it's crucial to run your Effect before the browser paint: for example, to measure and position a tooltip before the user sees it for the first time.
If your Effect must block the browser from [painting the screen,](/learn/render-and-commit#epilogue-browser-paint) replace `useEffect` with [`useLayoutEffect`](/reference/react/useLayoutEffect). Note that **this shouldn't be needed for the vast majority of Effects.** You'll only need this if it's crucial to run your Effect before the browser paint: for example, to measure and position a tooltip before the user sees it for the first time.

0
beta/src/content/apis/react/useEffectEvent.md → beta/src/content/reference/react/useEffectEvent.md

6
beta/src/content/apis/react/useId.md → beta/src/content/reference/react/useId.md

@ -167,7 +167,7 @@ input { margin: 5px; }
<Pitfall>
**`useId` requires an identical component tree on the server and the client** when you use [server rendering](/apis/react-dom/server). If the trees you render on the server and the client don't match exactly, the generated IDs won't match.
**`useId` requires an identical component tree on the server and the client** when you use [server rendering](/reference/react-dom/server). If the trees you render on the server and the client don't match exactly, the generated IDs won't match.
</Pitfall>
@ -177,7 +177,7 @@ input { margin: 5px; }
You might be wondering why `useId` is better than incrementing a global variable like `nextId++`.
The primary benefit of `useId` is that React ensures that it works with [server rendering.](/apis/react-dom/server) During server rendering, your components generate HTML output. Later, on the client, [hydration](/apis/react-dom/client/hydrateRoot) attaches your event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
The primary benefit of `useId` is that React ensures that it works with [server rendering.](/reference/react-dom/server) During server rendering, your components generate HTML output. Later, on the client, [hydration](/reference/react-dom/client/hydrateRoot) attaches your event handlers to the generated HTML. For hydration to work, the client output must match the server HTML.
This is very difficult to guarantee with an incrementing counter because the order in which the client components are hydrated may not match the order in which the server HTML was emitted. By calling `useId`, you ensure that hydration will work, and the output will match between the server and the client.
@ -222,7 +222,7 @@ This lets you avoid calling `useId` for every single element that needs a unique
### Specifying a shared prefix for all generated IDs {/*specifying-a-shared-prefix-for-all-generated-ids*/}
If you render multiple independent React applications on a single page, you may pass `identifierPrefix` as an option to your [`createRoot`](/apis/react-dom/client/createRoot#parameters) or [`hydrateRoot`](/apis/react-dom/client/hydrateRoot) calls. This ensures that the IDs generated by the two different apps never clash because every identifier generated with `useId` will start with the distinct prefix you've specified.
If you render multiple independent React applications on a single page, you may pass `identifierPrefix` as an option to your [`createRoot`](/reference/react-dom/client/createRoot#parameters) or [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) calls. This ensures that the IDs generated by the two different apps never clash because every identifier generated with `useId` will start with the distinct prefix you've specified.
<Sandpack>

6
beta/src/content/apis/react/useImperativeHandle.md → beta/src/content/reference/react/useImperativeHandle.md

@ -38,7 +38,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
#### Parameters {/*parameters*/}
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/apis/react/forwardRef#render-function)
* `ref`: The `ref` you received as the second argument from the [`forwardRef` render function.](/reference/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.
@ -54,7 +54,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
### Exposing a custom ref handle to the parent component {/*exposing-a-custom-ref-handle-to-the-parent-component*/}
By default, components don't expose their DOM nodes to parent components. For example, if you want the parent component of `MyInput` to [have access](/learn/manipulating-the-dom-with-refs) to the `<input>` DOM node, you have to opt in with [`forwardRef`:](/apis/react/forwardRef)
By default, components don't expose their DOM nodes to parent components. For example, if you want the parent component of `MyInput` to [have access](/learn/manipulating-the-dom-with-refs) to the `<input>` DOM node, you have to opt in with [`forwardRef`:](/reference/react/forwardRef)
```js {4}
import { forwardRef } from 'react';
@ -64,7 +64,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
});
```
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](/apis/react/forwardRef#exposing-a-dom-node-to-the-parent-component) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
With the code above, [a ref to `MyInput` will receive the `<input>` DOM node.](/reference/react/forwardRef#exposing-a-dom-node-to-the-parent-component) However, you can expose a custom value instead. To customize the exposed handle, call `useImperativeHandle` at the top level of your component:
```js {4-8}
import { forwardRef, useImperativeHandle } from 'react';

10
beta/src/content/apis/react/useInsertionEffect.md → beta/src/content/reference/react/useInsertionEffect.md

@ -4,13 +4,13 @@ title: 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.
`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`](/reference/react/useEffect) or [`useLayoutEffect`](/reference/react/useLayoutEffect) instead.
</Pitfall>
<Intro>
`useInsertionEffect` is a version of [`useEffect`](/apis/react/useEffect) that fires before any DOM mutations.
`useInsertionEffect` is a version of [`useEffect`](/reference/react/useEffect) that fires before any DOM mutations.
```js
useInsertionEffect(setup, dependencies?)
@ -28,7 +28,7 @@ useInsertionEffect(setup, dependencies?)
<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.
`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`](/reference/react/useEffect) or [`useLayoutEffect`](/reference/react/useLayoutEffect) instead.
</Pitfall>
@ -138,8 +138,8 @@ function useCSS(rule) {
#### How is this better than injecting styles during rendering or useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
If you insert styles during rendering and React is processing a [non-blocking update,](/apis/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) the browser will recalculate the styles every single frame while rendering a component tree, which can be **extremely slow.**
If you insert styles during rendering and React is processing a [non-blocking update,](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) the browser will recalculate the styles every single frame while rendering a component tree, which can be **extremely slow.**
`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.
`useInsertionEffect` is better than inserting styles during [`useLayoutEffect`](/reference/react/useLayoutEffect) or [`useEffect`](/reference/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>

20
beta/src/content/apis/react/useLayoutEffect.md → beta/src/content/reference/react/useLayoutEffect.md

@ -4,13 +4,13 @@ title: useLayoutEffect
<Pitfall>
`useLayoutEffect` can hurt performance. Prefer [`useEffect`](/apis/react/useEffect) when possible.
`useLayoutEffect` can hurt performance. Prefer [`useEffect`](/reference/react/useEffect) when possible.
</Pitfall>
<Intro>
`useLayoutEffect` is a version of [`useEffect`](/apis/react/useEffect) that fires before the browser repaints the screen.
`useLayoutEffect` is a version of [`useEffect`](/reference/react/useEffect) that fires before the browser repaints the screen.
```js
useLayoutEffect(setup, dependencies?)
@ -61,11 +61,11 @@ function Tooltip() {
* 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.
* 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](/reference/react/useEffect#removing-unnecessary-object-dependencies) and [function](/reference/react/useEffect#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](/reference/react/useEffect#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](/reference/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)
* 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`.](/reference/reac/useEffect)
---
@ -251,7 +251,7 @@ export default function TooltipContainer({ children, x, y, contentRef }) {
</Sandpack>
Notice that even though the `Tooltip` component has to render in two passes (first, with `tooltipHeight` initialized to `0` and then with the real measured height), you only see the final result. This is why you need `useLayoutEffect` instead of [`useEffect`](/apis/react/useEffect) for this example. Let's look at the difference in detail below.
Notice that even though the `Tooltip` component has to render in two passes (first, with `tooltipHeight` initialized to `0` and then with the real measured height), you only see the final result. This is why you need `useLayoutEffect` instead of [`useEffect`](/reference/react/useEffect) for this example. Let's look at the difference in detail below.
<Recipes titleText="useLayoutEffect vs useEffect" titleId="examples">
@ -404,7 +404,7 @@ export default function TooltipContainer({ children, x, y, contentRef }) {
#### `useEffect` does not block the browser {/*useeffect-does-not-block-the-browser*/}
Here is the same example, but with [`useEffect`](/apis/react/useEffect) instead of `useLayoutEffect`. If you're on a slower device, you might notice that sometimes the tooltip "flickers" and you briefly see its initial position before the corrected position.
Here is the same example, but with [`useEffect`](/reference/react/useEffect) instead of `useLayoutEffect`. If you're on a slower device, you might notice that sometimes the tooltip "flickers" and you briefly see its initial position before the corrected position.
<Sandpack>
@ -720,7 +720,7 @@ The purpose of `useLayoutEffect` is to let your component [use layout informatio
2. Measure the layout *before the browser repaints the screen.*
3. Render the final content using the layout information you've read.
When you or your framework uses [server rendering](/apis/react-dom/server), your React app renders to HTML on the server for the initial render. This lets you show the initial HTML before the JavaScript code loads.
When you or your framework uses [server rendering](/reference/react-dom/server), your React app renders to HTML on the server for the initial render. This lets you show the initial HTML before the JavaScript code loads.
The problem is that on the server, there is no layout information.
@ -730,13 +730,13 @@ Usually, components that rely on layout information don't need to render on the
However, if you're running into this problem, you have a few options:
1. You can replace `useLayoutEffect` with [`useEffect`.](/apis/react/useEffect) This tells React that it's okay to display the initial render result without blocking the paint (because the original HTML will become visible before your Effect runs).
1. You can replace `useLayoutEffect` with [`useEffect`.](/reference/react/useEffect) This tells React that it's okay to display the initial render result without blocking the paint (because the original HTML will become visible before your Effect runs).
2. You can [mark your component as client-only.](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content) This tells React to replace its content up to the closest [`<Suspense>`](/apis/react/Suspense) boundary with a loading fallback (for example, a spinner or a glimmer) during server rendering.
2. You can [mark your component as client-only.](/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content) This tells React to replace its content up to the closest [`<Suspense>`](/reference/react/Suspense) boundary with a loading fallback (for example, a spinner or a glimmer) during server rendering.
3. You can display different components on the server and on the client. One way to do this is to keep a boolean `isMounted` state that's initialized to `false`, and set it to `true` inside a `useEffect` call. Your rendering logic can then be like `return isMounted ? <RealContent /> : <FallbackContent />`. On the server and during the hydration, the user will see `FallbackContent` which should not call `useLayoutEffect`. Then React will replace it with `RealContent` which runs on the client only and can include `useLayoutEffect` calls.
4. If you synchronize your component with an external data store and rely on `useLayoutEffect` for different reasons than measuring layout, consider [`useSyncExternalStore`](/apis/react/useSyncExternalStore) instead which [supports server rendering.](/apis/react/useSyncExternalStore#adding-support-for-server-rendering)
4. If you synchronize your component with an external data store and rely on `useLayoutEffect` for different reasons than measuring layout, consider [`useSyncExternalStore`](/reference/react/useSyncExternalStore) instead which [supports server rendering.](/reference/react/useSyncExternalStore#adding-support-for-server-rendering)

34
beta/src/content/apis/react/useMemo.md → beta/src/content/reference/react/useMemo.md

@ -52,7 +52,7 @@ During subsequent renders, it will either return an already stored value from th
* `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.
* 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](/reference/react/useState#avoiding-recreating-the-initial-state) or a [ref](/reference/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate.
---
@ -127,7 +127,7 @@ console.timeEnd('filter array');
Keep in mind that your machine is probably faster than your users' so it's a good idea to test the performance with an artificial slowdown. For example, Chrome offers a [CPU Throttling](https://developer.chrome.com/blog/new-in-devtools-61/#throttling) option for this.
Also note that measuring performance in development will not give you the most accurate results. (For example, when [Strict Mode](/apis/react/StrictMode) is on, you will see each component render twice rather than once.) To get the most accurate timings, build your app for production and test it on a device like your users have.
Also note that measuring performance in development will not give you the most accurate results. (For example, when [Strict Mode](/reference/react/StrictMode) is on, you will see each component render twice rather than once.) To get the most accurate timings, build your app for production and test it on a device like your users have.
</DeepDive>
@ -140,8 +140,8 @@ If your app is like this site, and most interactions are coarse (like replacing
Optimizing with `useMemo` is only valuable in a few cases:
- The calculation you're putting in `useMemo` is noticeably slow, and its dependencies rarely change.
- You pass it as a prop to a component wrapped in [`memo`.](/apis/react/memo) You want to skip re-rendering if the value hasn't changed. Memoization lets your component re-render only when dependencies aren't the same.
- The value you're passing is later used as a dependency of some Hook. For example, maybe another `useMemo` calculation value depends on it. Or maybe you are depending on this value from [`useEffect.`](/apis/react/useEffect)
- You pass it as a prop to a component wrapped in [`memo`.](/reference/react/memo) You want to skip re-rendering if the value hasn't changed. Memoization lets your component re-render only when dependencies aren't the same.
- The value you're passing is later used as a dependency of some Hook. For example, maybe another `useMemo` calculation value depends on it. Or maybe you are depending on this value from [`useEffect.`](/reference/react/useEffect)
There is no benefit to wrapping a calculation in `useMemo` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value that's "always new" is enough to break memoization for an entire component.
@ -557,7 +557,7 @@ export default function TodoList({ todos, tab, theme }) {
You've noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `<List />` from your JSX, it feels fast. This tells you that it's worth trying to optimize the `List` component.
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `TodoList` re-renders with a different `theme`, the `List` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you've verified that a re-render is slow, you can tell `List` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/apis/react/memo)
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `TodoList` re-renders with a different `theme`, the `List` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you've verified that a re-render is slow, you can tell `List` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/reference/react/memo)
```js {3,5}
import { memo } from 'react';
@ -582,7 +582,7 @@ export default function TodoList({ todos, tab, theme }) {
}
```
**In the above example, the `filterTodos` function always creates a *different* array,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `List` props will never be the same, and your [`memo`](/apis/react/memo) optimization won't work. This is where `useMemo` comes in handy:
**In the above example, the `filterTodos` function always creates a *different* array,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `List` props will never be the same, and your [`memo`](/reference/react/memo) optimization won't work. This is where `useMemo` comes in handy:
```js {2-3,5,9-10}
export default function TodoList({ todos, tab, theme }) {
@ -601,13 +601,13 @@ export default function TodoList({ todos, tab, theme }) {
```
**By wrapping the `visibleTodos` calculation in `useMemo`, you ensure that it has the *same* value between the re-renders** (until dependencies change). You don't *have to* wrap a calculation in `useMemo` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](/apis/react/memo) and this lets it skip re-rendering. There are a few other reasons to add `useMemo` which are described further on this page.
**By wrapping the `visibleTodos` calculation in `useMemo`, you ensure that it has the *same* value between the re-renders** (until dependencies change). You don't *have to* wrap a calculation in `useMemo` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](/reference/react/memo) and this lets it skip re-rendering. There are a few other reasons to add `useMemo` which are described further on this page.
<DeepDive>
#### Memoizing individual JSX nodes {/*memoizing-individual-jsx-nodes*/}
Instead of wrapping `List` in [`memo`](/apis/react/memo), you could wrap the `<List />` JSX node itself in `useMemo`:
Instead of wrapping `List` in [`memo`](/reference/react/memo), you could wrap the `<List />` JSX node itself in `useMemo`:
```js {3,6}
export default function TodoList({ todos, tab, theme }) {
@ -627,7 +627,7 @@ A JSX node like `<List items={visibleTodos} />` is an object like `{ type: List,
However, if React sees the same exact JSX as during the previous render, it won't try to re-render your component. This is because JSX nodes are [immutable.](https://en.wikipedia.org/wiki/Immutable_object) A JSX node object could not have changed over time, so React knows it's safe to skip a re-render. However, for this to work, the node has to *actually be the same object*, not merely look the same in code. This is what `useMemo` does in this example.
Manually wrapping JSX nodes into `useMemo` is not convenient. For example, you can't do this conditionally. This is usually you would wrap components with [`memo`](/apis/react/memo) instead of wrapping JSX nodes.
Manually wrapping JSX nodes into `useMemo` is not convenient. For example, you can't do this conditionally. This is usually you would wrap components with [`memo`](/reference/react/memo) instead of wrapping JSX nodes.
</DeepDive>
@ -639,7 +639,7 @@ In this example, the `List` component is **artificially slowed down** so that yo
Switching the tabs feels slow because it forces the slowed down `List` to re-render. That's expected because the `tab` has changed, and so you need to reflect the user's new choice on the screen.
Next, try toggling the theme. **Thanks to `useMemo` together with [`memo`](/apis/react/memo), it’s fast despite the artificial slowdown!** The `List` skipped re-rendering because the `visibleItems` array has not changed since the last render. The `visibleItems` array has not changed because both `todos` and `tab` (which you pass as dependencies to `useMemo`) haven't changed since the last render.
Next, try toggling the theme. **Thanks to `useMemo` together with [`memo`](/reference/react/memo), it’s fast despite the artificial slowdown!** The `List` skipped re-rendering because the `visibleItems` array has not changed since the last render. The `visibleItems` array has not changed because both `todos` and `tab` (which you pass as dependencies to `useMemo`) haven't changed since the last render.
<Sandpack>
@ -1090,13 +1090,13 @@ function Dropdown({ allItems, text }) {
```
**Now your calculation depends on `text` directly (which is a string and can't "accidentally" be new like an object).**
You can use a similar approach to prevent [`useEffect`](/apis/react/useEffect) from firing again unnecessarily. Before you try to optimize dependencies with `useMemo`, see if you can make them unnecessary. [Read about removing Effect dependencies.](/learn/removing-effect-dependencies)
You can use a similar approach to prevent [`useEffect`](/reference/react/useEffect) from firing again unnecessarily. Before you try to optimize dependencies with `useMemo`, see if you can make them unnecessary. [Read about removing Effect dependencies.](/learn/removing-effect-dependencies)
---
### Memoizing a function {/*memoizing-a-function*/}
Suppose the `Form` component is wrapped in [`memo`.](/apis/react/memo) You want to pass a function to it as a prop:
Suppose the `Form` component is wrapped in [`memo`.](/reference/react/memo) You want to pass a function to it as a prop:
```js {2-7}
export default function ProductPage({ productId, referrer }) {
@ -1130,7 +1130,7 @@ export default function Page({ productId, referrer }) {
}
```
This looks clunky! **Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into [`useCallback`](/apis/react/useCallback) instead of `useMemo`** to avoid having to write an extra nested function:
This looks clunky! **Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into [`useCallback`](/reference/react/useCallback) instead of `useMemo`** to avoid having to write an extra nested function:
```js {2,7}
export default function Page({ productId, referrer }) {
@ -1145,7 +1145,7 @@ export default function Page({ productId, referrer }) {
}
```
The two examples above are completely equivalent. The only benefit to `useCallback` is that it lets you avoid writing an extra nested function inside. It doesn't do anything else. [Read more about `useCallback`.](/apis/react/useCallback)
The two examples above are completely equivalent. The only benefit to `useCallback` is that it lets you avoid writing an extra nested function inside. It doesn't do anything else. [Read more about `useCallback`.](/reference/react/useCallback)
---
@ -1153,7 +1153,7 @@ The two examples above are completely equivalent. The only benefit to `useCallba
### My calculation runs twice on every re-render {/*my-calculation-runs-twice-on-every-re-render*/}
In [Strict Mode](/apis/react/StrictMode), React will call some of your functions twice instead of once:
In [Strict Mode](/reference/react/StrictMode), React will call some of your functions twice instead of once:
```js {2,5,6}
function TodoList({ todos, tab }) {
@ -1280,7 +1280,7 @@ When you find which dependency is breaking memoization, either find a way to rem
### I need to call `useMemo` for each list item in a loop, but it's not allowed {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/}
Suppose the `Chart` component is wrapped in [`memo`](/apis/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useMemo` in a loop:
Suppose the `Chart` component is wrapped in [`memo`](/reference/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useMemo` in a loop:
```js {5-11}
function ReportList({ items }) {
@ -1324,7 +1324,7 @@ function Report({ item }) {
}
```
Alternatively, you could remove `useMemo` and instead wrap `Report` itself in [`memo`.](/apis/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
Alternatively, you could remove `useMemo` and instead wrap `Report` itself in [`memo`.](/reference/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```js {5,6,12}
function ReportList({ items }) {

6
beta/src/content/apis/react/useReducer.md → beta/src/content/reference/react/useReducer.md

@ -84,7 +84,7 @@ React will set the next state to the result of calling the `reducer` function yo
* 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)
* 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`.](/reference/react-dom/flushsync)
---
@ -157,7 +157,7 @@ button { display: block; margin-top: 10px; }
</Sandpack>
`useReducer` is very similar to [`useState`](/apis/react/useState), but it lets you move the state update logic from event handlers into a single function outside of your component. Read more about [choosing between `useState` and `useReducer`.](/learn/extracting-state-logic-into-a-reducer#comparing-usestate-and-usereducer)
`useReducer` is very similar to [`useState`](/reference/react/useState), but it lets you move the state update logic from event handlers into a single function outside of your component. Read more about [choosing between `useState` and `useReducer`.](/learn/extracting-state-logic-into-a-reducer#comparing-usestate-and-usereducer)
---
@ -1081,7 +1081,7 @@ If you can't find the cause of this error, click on the arrow next to the error
### My reducer or initializer function runs twice {/*my-reducer-or-initializer-function-runs-twice*/}
In [Strict Mode](/apis/react/StrictMode), React will call your reducer and initializer functions twice. This shouldn't break your code.
In [Strict Mode](/reference/react/StrictMode), React will call your reducer and initializer functions twice. This shouldn't break your code.
This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and reducer functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes and fix it.

8
beta/src/content/apis/react/useRef.md → beta/src/content/reference/react/useRef.md

@ -70,7 +70,7 @@ function Stopwatch() {
`useRef` returns a <CodeStep step={1}>ref object</CodeStep> with a single <CodeStep step={2}>`current` property</CodeStep> initially set to the <CodeStep step={3}>initial value</CodeStep> you provided.
On the next renders, `useRef` will return the same object. You can change its `current` property to store information and read it later. This might remind you of [state](/apis/react/useState), but there is an important difference.
On the next renders, `useRef` will return the same object. You can change its `current` property to store information and read it later. This might remind you of [state](/reference/react/useState), but there is an important difference.
**Changing a ref does not trigger a re-render.** This means refs are perfect for storing information that doesn't affect the visual output of your component. For example, if you need to store an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its <CodeStep step={2}>`current` property</CodeStep>:
@ -226,7 +226,7 @@ function MyComponent() {
}
```
If you *have to* read [or write](/apis/react/useState#storing-information-from-previous-renders) something during rendering, [use state](/apis/react/useState) instead.
If you *have to* read [or write](/reference/react/useState#storing-information-from-previous-renders) something during rendering, [use state](/reference/react/useState) instead.
When you break these rules, your component might still work, but most of the newer features we're adding to React will rely on these expectations. Read more about [keeping your components pure.](/learn/keeping-components-pure#where-you-can-cause-side-effects)
@ -448,7 +448,7 @@ button { display: block; margin-bottom: 20px; }
#### Exposing a ref to your own component {/*exposing-a-ref-to-your-own-component*/}
Sometimes, you may want to let the parent component manipulate the DOM inside of your component. For example, maybe you're writing a `MyInput` component, but you want the parent to be able to focus the input (which the parent has no access to). You can use a combination of `useRef` to hold the input and [`forwardRef`](/apis/react/forwardRef) to expose it to the parent component. Read a [detailed walkthrough](/learn/manipulating-the-dom-with-refs#accessing-another-components-dom-nodes) here.
Sometimes, you may want to let the parent component manipulate the DOM inside of your component. For example, maybe you're writing a `MyInput` component, but you want the parent to be able to focus the input (which the parent has no access to). You can use a combination of `useRef` to hold the input and [`forwardRef`](/reference/react/forwardRef) to expose it to the parent component. Read a [detailed walkthrough](/learn/manipulating-the-dom-with-refs#accessing-another-components-dom-nodes) here.
<Sandpack>
@ -573,7 +573,7 @@ export default function MyInput({ value, onChange }) {
}
```
And then wrap it in [`forwardRef`](/apis/react/forwardRef) like this:
And then wrap it in [`forwardRef`](/reference/react/forwardRef) like this:
```js {3,8}
import { forwardRef } from 'react';

6
beta/src/content/apis/react/useState.md → beta/src/content/reference/react/useState.md

@ -83,7 +83,7 @@ function handleClick() {
* 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)
* 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`.](/reference/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)
@ -1075,7 +1075,7 @@ Usually, you will update state in event handlers. However, in rare cases you mig
In most cases, you don't need this:
* **If the value you need can be computed entirely from the current props or other state, [remove that redundant state altogether.](/learn/choosing-the-state-structure#avoid-redundant-state)** If you're worried about recomputing too often, the [`useMemo` Hook](/apis/react/usememo) can help.
* **If the value you need can be computed entirely from the current props or other state, [remove that redundant state altogether.](/learn/choosing-the-state-structure#avoid-redundant-state)** If you're worried about recomputing too often, the [`useMemo` Hook](/reference/react/usememo) can help.
* If you want to reset the entire component tree's state, [pass a different `key` to your component.](#resetting-state-with-a-key)
* If you can, update all the relevant state in the event handlers.
@ -1219,7 +1219,7 @@ If you can't find the cause of this error, click on the arrow next to the error
### My initializer or updater function runs twice {/*my-initializer-or-updater-function-runs-twice*/}
In [Strict Mode](/apis/react/StrictMode), React will call some of your functions twice instead of once:
In [Strict Mode](/reference/react/StrictMode), React will call some of your functions twice instead of once:
```js {2,5-6,11-12}
function TodoList() {

12
beta/src/content/apis/react/useSyncExternalStore.md → beta/src/content/reference/react/useSyncExternalStore.md

@ -63,7 +63,7 @@ The current snapshot of the store which you can use in your rendering logic.
### Subscribing to an external store {/*subscribing-to-an-external-store*/}
Most of your React components will only read data from their [props,](/learn/passing-props-to-a-component) [state,](/apis/react/useState) and [context.](/apis/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes:
Most of your React components will only read data from their [props,](/learn/passing-props-to-a-component) [state,](/reference/react/useState) and [context.](/reference/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes:
* Third-party state management libraries that hold state outside of React.
* Browser APIs that expose a mutable value and events to subscribe to its changes.
@ -149,7 +149,7 @@ function emitChange() {
<Note>
When possible, we recommend to use the built-in React state with [`useState`](/apis/react/useState) and [`useReducer`](/apis/react/useReducer) instead. The `useExternalSyncStore` API is mostly useful if you need to integrate with existing non-React code.
When possible, we recommend to use the built-in React state with [`useState`](/reference/react/useState) and [`useReducer`](/reference/react/useReducer) instead. The `useExternalSyncStore` API is mostly useful if you need to integrate with existing non-React code.
</Note>
@ -306,7 +306,7 @@ function subscribe(callback) {
### Adding support for server rendering {/*adding-support-for-server-rendering*/}
If your React app uses [server rendering,](/apis/react-dom/server) your React components will also run outside the browser environment to generate the initial HTML. This creates a few challenges when connecting to an external store:
If your React app uses [server rendering,](/reference/react-dom/server) your React components will also run outside the browser environment to generate the initial HTML. This creates a few challenges when connecting to an external store:
- If you're connecting to a browser-only API, it won't work because it does not exist on the server.
- If you're connecting to a third-party data store, you'll need its data to match between the server and client.
@ -337,9 +337,9 @@ function subscribe(callback) {
The `getServerSnapshot` function is similar to `getSnapshot`, but it runs only in two situations:
- It runs on the server when generating the HTML.
- It runs on the client during [hydration](/apis/react-dom/client/hydrateRoot), i.e. when React takes the server HTML and makes it interactive.
- It runs on the client during [hydration](/reference/react-dom/client/hydrateRoot), i.e. when React takes the server HTML and makes it interactive.
This lets you provide the initial snapshot value which will be used before the app becomes interactive. If there is no meaningful initial value for the server rendering, you can [force the component to render only on the client.](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
This lets you provide the initial snapshot value which will be used before the app becomes interactive. If there is no meaningful initial value for the server rendering, you can [force the component to render only on the client.](/reference/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content)
<Note>
@ -410,7 +410,7 @@ function subscribe() {
}
```
Alternatively, wrap `subscribe` into [`useCallback`](/apis/react/useCallback) to only resubscribe when some argument changes:
Alternatively, wrap `subscribe` into [`useCallback`](/reference/react/useCallback) to only resubscribe when some argument changes:
```js {4-8}
function ChatIndicator({ userId }) {

18
beta/src/content/apis/react/useTransition.md → beta/src/content/reference/react/useTransition.md

@ -66,7 +66,7 @@ function TabContainer() {
#### 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)
* `scope`: A function that updates some state by calling one or more [`set` functions.](/reference/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*/}
@ -74,9 +74,9 @@ function TabContainer() {
#### 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.
* `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`](/reference/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.
* 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`](/reference/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.
@ -709,7 +709,7 @@ b { display: inline-block; margin-right: 10px; }
### Preventing unwanted loading indicators {/*preventing-unwanted-loading-indicators*/}
In this example, the `PostsTab` component fetches some data using a [Suspense-enabled](/apis/react/Suspense) data source. When you click the "Posts" tab, the `PostsTab` component *suspends*, causing the closest loading fallback to be displayed:
In this example, the `PostsTab` component fetches some data using a [Suspense-enabled](/reference/react/Suspense) data source. When you click the "Posts" tab, the `PostsTab` component *suspends*, causing the closest loading fallback to be displayed:
<Sandpack>
@ -1087,11 +1087,11 @@ b { display: inline-block; margin-right: 10px; }
</Sandpack>
[Read more about using transitions with Suspense.](/apis/react/Suspense#preventing-already-revealed-content-from-hiding)
[Read more about using transitions with Suspense.](/reference/react/Suspense#preventing-already-revealed-content-from-hiding)
<Note>
Transitions will only "wait" long enough to avoid hiding *already revealed* content (like the tab container). For example, if the Posts tab had a [nested `<Suspense>` boundary,](/apis/react/Suspense#revealing-nested-content-as-it-loads) the transition would not "wait" for it.
Transitions will only "wait" long enough to avoid hiding *already revealed* content (like the tab container). For example, if the Posts tab had a [nested `<Suspense>` boundary,](/reference/react/Suspense#revealing-nested-content-as-it-loads) the transition would not "wait" for it.
</Note>
@ -1495,7 +1495,7 @@ main {
<Note>
[Suspense-enabled](/apis/react/Suspense) routers are expected to wrap the navigation updates into transitions by default.
[Suspense-enabled](/reference/react/Suspense) routers are expected to wrap the navigation updates into transitions by default.
</Note>
@ -1523,7 +1523,7 @@ return <input value={text} onChange={handleChange} />;
This is because transitions are non-blocking, but updating an input in response to the change event should happen synchronously. If you want to run a transition in response to typing, you have two options:
1. You can declare two separate state variables: one for the input state (which always updates synchronously), and one that you will update in a transition. This lets you control the input using the synchronous state, and pass the transition state variable (which will "lag behind" the input) to the rest of your rendering logic.
2. Alternatively, you can have one state variable, and add [`useDeferredValue`](/apis/react/useDeferredValue) which will "lag behind" the real value. It will trigger non-blocking re-renders to "catch up" with the new value automatically.
2. Alternatively, you can have one state variable, and add [`useDeferredValue`](/reference/react/useDeferredValue) which will "lag behind" the real value. It will trigger non-blocking re-renders to "catch up" with the new value automatically.
---
@ -1586,7 +1586,7 @@ startTransition(() => {
### I want to call `useTransition` from outside a component {/*i-want-to-call-usetransition-from-outside-a-component*/}
You can't call `useTransition` outside a component because it's a Hook. In this case, use the standalone [`startTransition`](/apis/react/startTransition) method instead. It works the same way, but it doesn't provide the `isPending` indicator.
You can't call `useTransition` outside a component because it's a Hook. In this case, use the standalone [`startTransition`](/reference/react/startTransition) method instead. It works the same way, but it doesn't provide the `isPending` indicator.
---

6
beta/src/hooks/useActiveSection.ts

@ -4,10 +4,10 @@
import {useRouter} from 'next/router';
export function useActiveSection(): 'learn' | 'apis' | 'home' {
export function useActiveSection(): 'learn' | 'reference' | 'home' {
const {asPath} = useRouter();
if (asPath.startsWith('/apis')) {
return 'apis';
if (asPath.startsWith('/reference')) {
return 'reference';
} else if (asPath.startsWith('/learn')) {
return 'learn';
} else {

6
beta/src/hooks/usePathWithoutQuerystring.ts

@ -4,12 +4,12 @@
import {useRouter} from 'next/router';
export function useActiveSection(): 'learn' | 'apis' | 'home' {
export function useActiveSection(): 'learn' | 'reference' | 'home' {
const {asPath} = useRouter();
if (asPath.startsWith('/learn')) {
return 'learn';
} else if (asPath.startsWith('/apis')) {
return 'apis';
} else if (asPath.startsWith('/reference')) {
return 'reference';
} else {
return 'home';
}

122
beta/src/sidebarAPIs.json → beta/src/sidebarReference.json

@ -1,7 +1,7 @@
{
"title": "API Reference",
"heading": true,
"path": "/apis",
"path": "/reference",
"routes": [
{
"heading": true,
@ -9,259 +9,259 @@
"routes": [
{
"title": "react: Hooks",
"path": "/apis/react",
"path": "/reference/react",
"routes": [
{
"title": "useCallback",
"path": "/apis/react/useCallback"
"path": "/reference/react/useCallback"
},
{
"title": "useContext",
"path": "/apis/react/useContext"
"path": "/reference/react/useContext"
},
{
"title": "useDebugValue",
"path": "/apis/react/useDebugValue"
"path": "/reference/react/useDebugValue"
},
{
"title": "useDeferredValue",
"path": "/apis/react/useDeferredValue"
"path": "/reference/react/useDeferredValue"
},
{
"title": "useEffect",
"path": "/apis/react/useEffect"
"path": "/reference/react/useEffect"
},
{
"title": "useId",
"path": "/apis/react/useId"
"path": "/reference/react/useId"
},
{
"title": "useImperativeHandle",
"path": "/apis/react/useImperativeHandle"
"path": "/reference/react/useImperativeHandle"
},
{
"title": "useInsertionEffect",
"path": "/apis/react/useInsertionEffect"
"path": "/reference/react/useInsertionEffect"
},
{
"title": "useLayoutEffect",
"path": "/apis/react/useLayoutEffect"
"path": "/reference/react/useLayoutEffect"
},
{
"title": "useMemo",
"path": "/apis/react/useMemo"
"path": "/reference/react/useMemo"
},
{
"title": "useReducer",
"path": "/apis/react/useReducer"
"path": "/reference/react/useReducer"
},
{
"title": "useRef",
"path": "/apis/react/useRef"
"path": "/reference/react/useRef"
},
{
"title": "useState",
"path": "/apis/react/useState"
"path": "/reference/react/useState"
},
{
"title": "useSyncExternalStore",
"path": "/apis/react/useSyncExternalStore"
"path": "/reference/react/useSyncExternalStore"
},
{
"title": "useTransition",
"path": "/apis/react/useTransition"
"path": "/reference/react/useTransition"
}
]
},
{
"title": "react: Components",
"path": "/apis/react/components",
"path": "/reference/react/components",
"routes": [
{
"title": "<Fragment> (<>)",
"path": "/apis/react/Fragment"
"path": "/reference/react/Fragment"
},
{
"title": "<Profiler>",
"path": "/apis/react/Profiler"
"path": "/reference/react/Profiler"
},
{
"title": "<StrictMode>",
"path": "/apis/react/StrictMode"
"path": "/reference/react/StrictMode"
},
{
"title": "<Suspense>",
"path": "/apis/react/Suspense"
"path": "/reference/react/Suspense"
}
]
},
{
"title": "react: APIs",
"path": "/apis/react/apis",
"path": "/reference/react/apis",
"routes": [
{
"title": "createContext",
"path": "/apis/react/createContext"
"path": "/reference/react/createContext"
},
{
"title": "forwardRef",
"path": "/apis/react/forwardRef"
"path": "/reference/react/forwardRef"
},
{
"title": "lazy",
"path": "/apis/react/lazy"
"path": "/reference/react/lazy"
},
{
"title": "memo",
"path": "/apis/react/memo"
"path": "/reference/react/memo"
},
{
"title": "startTransition",
"path": "/apis/react/startTransition"
"path": "/reference/react/startTransition"
}
]
},
{
"title": "react-dom: Components",
"path": "/apis/react-dom/components",
"path": "/reference/react-dom/components",
"hasSeparator": true,
"routes": [
{
"title": "Common (e.g. <div>)",
"path": "/apis/react-dom/components/common"
"path": "/reference/react-dom/components/common"
},
{
"title": "<input>",
"path": "/apis/react-dom/components/input"
"path": "/reference/react-dom/components/input"
},
{
"title": "<option>",
"path": "/apis/react-dom/components/option"
"path": "/reference/react-dom/components/option"
},
{
"title": "<progress>",
"path": "/apis/react-dom/components/progress"
"path": "/reference/react-dom/components/progress"
},
{
"title": "<select>",
"path": "/apis/react-dom/components/select"
"path": "/reference/react-dom/components/select"
},
{
"title": "<textarea>",
"path": "/apis/react-dom/components/textarea"
"path": "/reference/react-dom/components/textarea"
}
]
},
{
"title": "react-dom: APIs",
"path": "/apis/react-dom",
"path": "/reference/react-dom",
"routes": [
{
"title": "createPortal",
"path": "/apis/react-dom/createPortal"
"path": "/reference/react-dom/createPortal"
},
{
"title": "flushSync",
"path": "/apis/react-dom/flushSync"
"path": "/reference/react-dom/flushSync"
},
{
"title": "findDOMNode",
"path": "/apis/react-dom/findDOMNode"
"path": "/reference/react-dom/findDOMNode"
},
{
"title": "hydrate",
"path": "/apis/react-dom/hydrate"
"path": "/reference/react-dom/hydrate"
},
{
"title": "render",
"path": "/apis/react-dom/render"
"path": "/reference/react-dom/render"
},
{
"title": "unmountComponentAtNode",
"path": "/apis/react-dom/unmountComponentAtNode"
"path": "/reference/react-dom/unmountComponentAtNode"
}
]
},
{
"title": "react-dom\/client",
"path": "/apis/react-dom/client",
"path": "/reference/react-dom/client",
"routes": [
{
"title": "createRoot",
"path": "/apis/react-dom/client/createRoot"
"path": "/reference/react-dom/client/createRoot"
},
{
"title": "hydrateRoot",
"path": "/apis/react-dom/client/hydrateRoot"
"path": "/reference/react-dom/client/hydrateRoot"
}
]
},
{
"title": "react-dom\/server",
"path": "/apis/react-dom/server",
"path": "/reference/react-dom/server",
"routes": [
{
"title": "renderToNodeStream",
"path": "/apis/react-dom/server/renderToNodeStream"
"path": "/reference/react-dom/server/renderToNodeStream"
},
{
"title": "renderToPipeableStream",
"path": "/apis/react-dom/server/renderToPipeableStream"
"path": "/reference/react-dom/server/renderToPipeableStream"
},
{
"title": "renderToReadableStream",
"path": "/apis/react-dom/server/renderToReadableStream"
"path": "/reference/react-dom/server/renderToReadableStream"
},
{
"title": "renderToStaticMarkup",
"path": "/apis/react-dom/server/renderToStaticMarkup"
"path": "/reference/react-dom/server/renderToStaticMarkup"
},
{
"title": "renderToStaticNodeStream",
"path": "/apis/react-dom/server/renderToStaticNodeStream"
"path": "/reference/react-dom/server/renderToStaticNodeStream"
},
{
"title": "renderToString",
"path": "/apis/react-dom/server/renderToString"
"path": "/reference/react-dom/server/renderToString"
}
]
},
{
"title": "react: Legacy APIs",
"path": "/apis/react/legacy",
"path": "/reference/react/legacy",
"hasSeparator": true,
"routes": [
{
"title": "Children",
"path": "/apis/react/Children"
"path": "/reference/react/Children"
},
{
"title": "cloneElement",
"path": "/apis/react/cloneElement"
"path": "/reference/react/cloneElement"
},
{
"title": "Component",
"path": "/apis/react/Component"
"path": "/reference/react/Component"
},
{
"title": "createElement",
"path": "/apis/react/createElement"
"path": "/reference/react/createElement"
},
{
"title": "createFactory",
"path": "/apis/react/createFactory"
"path": "/reference/react/createFactory"
},
{
"title": "createRef",
"path": "/apis/react/createRef"
"path": "/reference/react/createRef"
},
{
"title": "isValidElement",
"path": "/apis/react/isValidElement"
"path": "/reference/react/isValidElement"
},
{
"title": "PureComponent",
"path": "/apis/react/PureComponent"
"path": "/reference/react/PureComponent"
}
]
}

48
beta/vercel.json

@ -4,11 +4,6 @@
},
"trailingSlash": false,
"redirects": [
{
"source": "/reference/:path*",
"destination": "/apis/:path*",
"permanent": false
},
{
"source": "/tips/controlled-input-null-value.html",
"destination": "/docs/forms.html#controlled-input-null-value",
@ -255,48 +250,13 @@
"permanent": false
},
{
"source": "/apis/createcontext",
"destination": "/apis/react/createContext",
"permanent": true
},
{
"source": "/apis/usecontext",
"destination": "/apis/react/useContext",
"permanent": true
},
{
"source": "/apis/usereducer",
"destination": "/apis/react/useReducer",
"permanent": true
},
{
"source": "/apis/useref",
"destination": "/apis/react/useRef",
"permanent": true
},
{
"source": "/apis/usestate",
"destination": "/apis/react/useState",
"permanent": true
},
{
"source": "/apis",
"destination": "/apis/react",
"permanent": true
},
{
"source": "/apis/reactdom",
"destination": "/apis/react-dom",
"permanent": true
},
{
"source": "/apis/render",
"destination": "/apis/react-dom/render",
"source": "/apis/:path*",
"destination": "/reference/:path*",
"permanent": true
},
{
"source": "/apis/createportal",
"destination": "/apis/react-dom/createPortal",
"source": "/reference",
"destination": "/reference/react",
"permanent": true
}
],

Loading…
Cancel
Save