From c79307666bb02b8d74d60c413cf41ec6d54c97ca Mon Sep 17 00:00:00 2001 From: dan Date: Sun, 25 Dec 2022 21:01:34 +0000 Subject: [PATCH] [Beta] APIs -> Reference (#5400) * [Beta] APIs -> Reference * oops --- beta/src/components/Layout/Footer.tsx | 8 +- beta/src/components/Layout/Nav/Nav.tsx | 18 +-- beta/src/components/Layout/Page.tsx | 6 +- beta/src/components/MDX/HomepageHero.tsx | 2 +- beta/src/content/apis/react-dom/index.md | 43 ------ beta/src/content/apis/react/apis.md | 21 --- beta/src/content/apis/react/components.md | 20 --- beta/src/content/apis/react/legacy.md | 34 ----- .../content/learn/add-react-to-a-website.md | 2 +- .../src/content/learn/adding-interactivity.md | 2 +- beta/src/content/learn/index.md | 4 +- .../content/learn/keeping-components-pure.md | 4 +- .../learn/lifecycle-of-reactive-effects.md | 4 +- .../learn/manipulating-the-dom-with-refs.md | 4 +- .../learn/reacting-to-input-with-state.md | 2 +- .../learn/removing-effect-dependencies.md | 4 +- beta/src/content/learn/render-and-commit.md | 2 +- beta/src/content/learn/rendering-lists.md | 2 +- .../learn/reusing-logic-with-custom-hooks.md | 8 +- .../learn/separating-events-from-effects.md | 2 +- .../learn/state-a-components-memory.md | 6 +- .../learn/synchronizing-with-effects.md | 16 +-- beta/src/content/learn/thinking-in-react.md | 2 +- .../src/content/learn/tutorial-tic-tac-toe.md | 2 +- .../learn/updating-objects-in-state.md | 2 +- .../content/learn/writing-markup-with-jsx.md | 2 +- .../learn/you-might-not-need-an-effect.md | 12 +- .../react-dom/client/createRoot.md | 22 ++-- .../react-dom/client/hydrateRoot.md | 18 +-- .../react-dom/client/index.md | 4 +- .../react-dom/components/common.md | 18 +-- .../react-dom/components/index.md | 20 +-- .../react-dom/components/input.md | 16 +-- .../react-dom/components/option.md | 12 +- .../react-dom/components/progress.md | 2 +- .../react-dom/components/select.md | 12 +- .../react-dom/components/textarea.md | 14 +- .../react-dom/createPortal.md | 4 +- .../react-dom/findDOMNode.md | 16 +-- .../react-dom/flushSync.md | 0 .../{apis => reference}/react-dom/hydrate.md | 16 +-- beta/src/content/reference/react-dom/index.md | 43 ++++++ .../{apis => reference}/react-dom/render.md | 20 +-- .../react-dom/server/index.md | 12 +- .../react-dom/server/renderToNodeStream.md | 14 +- .../server/renderToPipeableStream.md | 22 ++-- .../server/renderToReadableStream.md | 22 ++-- .../react-dom/server/renderToStaticMarkup.md | 4 +- .../server/renderToStaticNodeStream.md | 4 +- .../react-dom/server/renderToString.md | 14 +- .../react-dom/unmountComponentAtNode.md | 4 +- .../{apis => reference}/react/Children.md | 8 +- .../{apis => reference}/react/Component.md | 68 +++++----- .../{apis => reference}/react/Fragment.md | 0 .../{apis => reference}/react/Profiler.md | 2 +- .../react/PureComponent.md | 14 +- .../{apis => reference}/react/StrictMode.md | 16 +-- .../{apis => reference}/react/Suspense.md | 20 +-- beta/src/content/reference/react/apis.md | 21 +++ .../{apis => reference}/react/cloneElement.md | 8 +- .../src/content/reference/react/components.md | 20 +++ .../react/createContext.md | 14 +- .../react/createElement.md | 4 +- .../react/createFactory.md | 4 +- .../{apis => reference}/react/createRef.md | 16 +-- .../{apis => reference}/react/forwardRef.md | 8 +- .../{apis => reference}/react/index.md | 40 +++--- .../react/isValidElement.md | 8 +- .../content/{apis => reference}/react/lazy.md | 8 +- beta/src/content/reference/react/legacy.md | 34 +++++ .../content/{apis => reference}/react/memo.md | 8 +- .../react/startTransition.md | 10 +- .../{apis => reference}/react/useCallback.md | 32 ++--- .../{apis => reference}/react/useContext.md | 16 +-- .../react/useDebugValue.md | 0 .../react/useDeferredValue.md | 12 +- .../{apis => reference}/react/useEffect.md | 18 +-- .../react/useEffectEvent.md | 0 .../{apis => reference}/react/useId.md | 6 +- .../react/useImperativeHandle.md | 6 +- .../react/useInsertionEffect.md | 10 +- .../react/useLayoutEffect.md | 20 +-- .../{apis => reference}/react/useMemo.md | 34 ++--- .../{apis => reference}/react/useReducer.md | 6 +- .../{apis => reference}/react/useRef.md | 8 +- .../{apis => reference}/react/useState.md | 6 +- .../react/useSyncExternalStore.md | 12 +- .../react/useTransition.md | 18 +-- beta/src/hooks/useActiveSection.ts | 6 +- beta/src/hooks/usePathWithoutQuerystring.ts | 6 +- ...sidebarAPIs.json => sidebarReference.json} | 122 +++++++++--------- beta/vercel.json | 48 +------ 92 files changed, 623 insertions(+), 661 deletions(-) delete mode 100644 beta/src/content/apis/react-dom/index.md delete mode 100644 beta/src/content/apis/react/apis.md delete mode 100644 beta/src/content/apis/react/components.md delete mode 100644 beta/src/content/apis/react/legacy.md rename beta/src/content/{apis => reference}/react-dom/client/createRoot.md (88%) rename beta/src/content/{apis => reference}/react-dom/client/hydrateRoot.md (92%) rename beta/src/content/{apis => reference}/react-dom/client/index.md (65%) rename beta/src/content/{apis => reference}/react-dom/components/common.md (97%) rename beta/src/content/{apis => reference}/react-dom/components/index.md (96%) rename beta/src/content/{apis => reference}/react-dom/components/input.md (93%) rename beta/src/content/{apis => reference}/react-dom/components/option.md (74%) rename beta/src/content/{apis => reference}/react-dom/components/progress.md (94%) rename beta/src/content/{apis => reference}/react-dom/components/select.md (93%) rename beta/src/content/{apis => reference}/react-dom/components/textarea.md (91%) rename beta/src/content/{apis => reference}/react-dom/createPortal.md (97%) rename beta/src/content/{apis => reference}/react-dom/findDOMNode.md (92%) rename beta/src/content/{apis => reference}/react-dom/flushSync.md (100%) rename beta/src/content/{apis => reference}/react-dom/hydrate.md (83%) create mode 100644 beta/src/content/reference/react-dom/index.md rename beta/src/content/{apis => reference}/react-dom/render.md (80%) rename beta/src/content/{apis => reference}/react-dom/server/index.md (57%) rename beta/src/content/{apis => reference}/react-dom/server/renderToNodeStream.md (74%) rename beta/src/content/{apis => reference}/react-dom/server/renderToPipeableStream.md (93%) rename beta/src/content/{apis => reference}/react-dom/server/renderToReadableStream.md (93%) rename beta/src/content/{apis => reference}/react-dom/server/renderToStaticMarkup.md (87%) rename beta/src/content/{apis => reference}/react-dom/server/renderToStaticNodeStream.md (88%) rename beta/src/content/{apis => reference}/react-dom/server/renderToString.md (78%) rename beta/src/content/{apis => reference}/react-dom/unmountComponentAtNode.md (95%) rename beta/src/content/{apis => reference}/react/Children.md (95%) rename beta/src/content/{apis => reference}/react/Component.md (91%) rename beta/src/content/{apis => reference}/react/Fragment.md (100%) rename beta/src/content/{apis => reference}/react/Profiler.md (95%) rename beta/src/content/{apis => reference}/react/PureComponent.md (78%) rename beta/src/content/{apis => reference}/react/StrictMode.md (93%) rename beta/src/content/{apis => reference}/react/Suspense.md (96%) create mode 100644 beta/src/content/reference/react/apis.md rename beta/src/content/{apis => reference}/react/cloneElement.md (96%) create mode 100644 beta/src/content/reference/react/components.md rename beta/src/content/{apis => reference}/react/createContext.md (89%) rename beta/src/content/{apis => reference}/react/createElement.md (97%) rename beta/src/content/{apis => reference}/react/createFactory.md (96%) rename beta/src/content/{apis => reference}/react/createRef.md (72%) rename beta/src/content/{apis => reference}/react/forwardRef.md (95%) rename beta/src/content/{apis => reference}/react/index.md (60%) rename beta/src/content/{apis => reference}/react/isValidElement.md (83%) rename beta/src/content/{apis => reference}/react/lazy.md (93%) create mode 100644 beta/src/content/reference/react/legacy.md rename beta/src/content/{apis => reference}/react/memo.md (97%) rename beta/src/content/{apis => reference}/react/startTransition.md (74%) rename beta/src/content/{apis => reference}/react/useCallback.md (91%) rename beta/src/content/{apis => reference}/react/useContext.md (96%) rename beta/src/content/{apis => reference}/react/useDebugValue.md (100%) rename beta/src/content/{apis => reference}/react/useDeferredValue.md (95%) rename beta/src/content/{apis => reference}/react/useEffect.md (97%) rename beta/src/content/{apis => reference}/react/useEffectEvent.md (100%) rename beta/src/content/{apis => reference}/react/useId.md (89%) rename beta/src/content/{apis => reference}/react/useImperativeHandle.md (95%) rename beta/src/content/{apis => reference}/react/useInsertionEffect.md (84%) rename beta/src/content/{apis => reference}/react/useLayoutEffect.md (91%) rename beta/src/content/{apis => reference}/react/useMemo.md (94%) rename beta/src/content/{apis => reference}/react/useReducer.md (98%) rename beta/src/content/{apis => reference}/react/useRef.md (96%) rename beta/src/content/{apis => reference}/react/useState.md (99%) rename beta/src/content/{apis => reference}/react/useSyncExternalStore.md (92%) rename beta/src/content/{apis => reference}/react/useTransition.md (96%) rename beta/src/{sidebarAPIs.json => sidebarReference.json} (57%) diff --git a/beta/src/components/Layout/Footer.tsx b/beta/src/components/Layout/Footer.tsx index 87a21262d..dc2ac0071 100644 --- a/beta/src/components/Layout/Footer.tsx +++ b/beta/src/components/Layout/Footer.tsx @@ -112,11 +112,13 @@ export function Footer() {
- + API Reference - React APIs - React DOM APIs + React APIs + + React DOM APIs +
diff --git a/beta/src/components/Layout/Nav/Nav.tsx b/beta/src/components/Layout/Nav/Nav.tsx index 99e553dc6..81d8f4c4b 100644 --- a/beta/src/components/Layout/Nav/Nav.tsx +++ b/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 - - API + + Reference
@@ -318,9 +318,9 @@ export default function Nav() { Learn selectTab('apis')}> - API + isActive={tab === 'reference'} + onClick={() => selectTab('reference')}> + Reference
)} diff --git a/beta/src/components/Layout/Page.tsx b/beta/src/components/Layout/Page.tsx index d3ba5ed01..cafba9d36 100644 --- a/beta/src/components/Layout/Page.tsx +++ b/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 ( diff --git a/beta/src/components/MDX/HomepageHero.tsx b/beta/src/components/MDX/HomepageHero.tsx index 4cfdecdd9..330a908a9 100644 --- a/beta/src/components/MDX/HomepageHero.tsx +++ b/beta/src/components/MDX/HomepageHero.tsx @@ -29,7 +29,7 @@ function HomepageHero() {
- +

Look up the API of React Hooks, and see their shape with color-coded signatures. diff --git a/beta/src/content/apis/react-dom/index.md b/beta/src/content/apis/react-dom/index.md deleted file mode 100644 index 4ec3ae3b0..000000000 --- a/beta/src/content/apis/react-dom/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: react-dom ---- - - - -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. - - - ---- - -## 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*/} - - - -These APIs will be removed in a future major version of React. - - - -* [`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) - diff --git a/beta/src/content/apis/react/apis.md b/beta/src/content/apis/react/apis.md deleted file mode 100644 index 84fdd2228..000000000 --- a/beta/src/content/apis/react/apis.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: "react: APIs" ---- - - - -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. - - - - - ---- - -## 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) diff --git a/beta/src/content/apis/react/components.md b/beta/src/content/apis/react/components.md deleted file mode 100644 index e70c53157..000000000 --- a/beta/src/content/apis/react/components.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: "react: Components" ---- - - - -React exposes a few built-in components that you can use in your JSX. - - - - - ---- - -## Built-in React components {/*built-in-react-components*/} - -* [``](/apis/react/Fragment), alternatively written as `<>...`, lets you group multiple JSX nodes together. -* [``](/apis/react/Profiler) lets you measure rendering performance of a React tree programmatically. -* [``](/apis/react/Suspense) lets you display a fallback while the child components are loading. -* [``](/apis/react/StrictMode) enables extra development-only checks that help you find bugs early. diff --git a/beta/src/content/apis/react/legacy.md b/beta/src/content/apis/react/legacy.md deleted file mode 100644 index 5baa6d811..000000000 --- a/beta/src/content/apis/react/legacy.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: "react: Legacy APIs" ---- - - - -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. - - - ---- - -## 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*/} - - - -These APIs will be removed in a future major version of React. - - - -* [`createFactory`](/apis/react/createFactory) lets you create a function that produces React elements of a certain type. \ No newline at end of file diff --git a/beta/src/content/learn/add-react-to-a-website.md b/beta/src/content/learn/add-react-to-a-website.md index c60368508..4c1383fa0 100644 --- a/beta/src/content/learn/add-react-to-a-website.md +++ b/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: diff --git a/beta/src/content/learn/adding-interactivity.md b/beta/src/content/learn/adding-interactivity.md index 08d20551e..bdf75623c 100644 --- a/beta/src/content/learn/adding-interactivity.md +++ b/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); diff --git a/beta/src/content/learn/index.md b/beta/src/content/learn/index.md index 260bf30b9..720b7c08e 100644 --- a/beta/src/content/learn/index.md +++ b/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. diff --git a/beta/src/content/learn/keeping-components-pure.md b/beta/src/content/learn/keeping-components-pure.md index 81df4ebfe..60760edc5 100644 --- a/beta/src/content/learn/keeping-components-pure.md +++ b/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. diff --git a/beta/src/content/learn/lifecycle-of-reactive-effects.md b/beta/src/content/learn/lifecycle-of-reactive-effects.md index 00b6fa048..803e7be9e 100644 --- a/beta/src/content/learn/lifecycle-of-reactive-effects.md +++ b/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 -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. diff --git a/beta/src/content/learn/manipulating-the-dom-with-refs.md b/beta/src/content/learn/manipulating-the-dom-with-refs.md index 13b94b7dd..2adee47ac 100644 --- a/beta/src/content/learn/manipulating-the-dom-with-refs.md +++ b/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 { -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

  • 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)`: diff --git a/beta/src/content/learn/render-and-commit.md b/beta/src/content/learn/render-and-commit.md index ea593873f..e54485a74 100644 --- a/beta/src/content/learn/render-and-commit.md +++ b/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.) diff --git a/beta/src/content/learn/rendering-lists.md b/beta/src/content/learn/rendering-lists.md index 9f3aa4e47..0231961b7 100644 --- a/beta/src/content/learn/rendering-lists.md +++ b/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 `
    `, or use the slightly longer and [more explicit `` 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 `
    `, or use the slightly longer and [more explicit `` syntax:](/reference/react/Fragment#rendering-a-list-of-fragments) ```js import { Fragment } from 'react'; diff --git a/beta/src/content/learn/reusing-logic-with-custom-hooks.md b/beta/src/content/learn/reusing-logic-with-custom-hooks.md index 571aa7dfe..d4a138ed7 100644 --- a/beta/src/content/learn/reusing-logic-with-custom-hooks.md +++ b/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() { -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: diff --git a/beta/src/content/learn/separating-events-from-effects.md b/beta/src/content/learn/separating-events-from-effects.md index becdd0e16..ba1029d8c 100644 --- a/beta/src/content/learn/separating-events-from-effects.md +++ b/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 -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'; diff --git a/beta/src/content/learn/state-a-components-memory.md b/beta/src/content/learn/state-a-components-memory.md index 5c4a96495..e67cf0a51 100644 --- a/beta/src/content/learn/state-a-components-memory.md +++ b/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 -* 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); diff --git a/beta/src/content/learn/synchronizing-with-effects.md b/beta/src/content/learn/synchronizing-with-effects.md index ece12f854..8fabc2b7c 100644 --- a/beta/src/content/learn/synchronizing-with-effects.md +++ b/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; } -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. @@ -1371,7 +1371,7 @@ body { -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. diff --git a/beta/src/content/learn/thinking-in-react.md b/beta/src/content/learn/thinking-in-react.md index b2d29696e..82dc4c0fc 100644 --- a/beta/src/content/learn/thinking-in-react.md +++ b/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 }) { diff --git a/beta/src/content/learn/tutorial-tic-tac-toe.md b/beta/src/content/learn/tutorial-tic-tac-toe.md index 900d2e48c..2d0fcc27f 100644 --- a/beta/src/content/learn/tutorial-tic-tac-toe.md +++ b/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*/} diff --git a/beta/src/content/learn/updating-objects-in-state.md b/beta/src/content/learn/updating-objects-in-state.md index dab499204..df8bffaaa 100644 --- a/beta/src/content/learn/updating-objects-in-state.md +++ b/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. diff --git a/beta/src/content/learn/writing-markup-with-jsx.md b/beta/src/content/learn/writing-markup-with-jsx.md index deb698034..9030d1a8f 100644 --- a/beta/src/content/learn/writing-markup-with-jsx.md +++ b/beta/src/content/learn/writing-markup-with-jsx.md @@ -169,7 +169,7 @@ If you don't want to add an extra `
    ` 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. diff --git a/beta/src/content/learn/you-might-not-need-an-effect.md b/beta/src/content/learn/you-might-not-need-an-effect.md index d6c32232b..6b4f75931 100644 --- a/beta/src/content/learn/you-might-not-need-an-effect.md +++ b/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) @@ -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. @@ -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*/} diff --git a/beta/src/content/apis/react-dom/client/createRoot.md b/beta/src/content/reference/react-dom/client/createRoot.md similarity index 88% rename from beta/src/content/apis/react-dom/client/createRoot.md rename to beta/src/content/reference/react-dom/client/createRoot.md index b8dd10e7b..08de42961 100644 --- a/beta/src/content/apis/react-dom/client/createRoot.md +++ b/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 `` 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 ``, 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 ``, 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 `` 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) @@ -196,13 +196,13 @@ When your HTML is empty, the user sees a blank page until the app's JavaScript c
    ``` -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).*
    -**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. @@ -332,7 +332,7 @@ export default function App({counter}) { -It is uncommon to call `render` multiple times. Usually, you'll [update state](/apis/react/useState) inside one of the components instead. +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'; diff --git a/beta/src/content/apis/react-dom/client/hydrateRoot.md b/beta/src/content/reference/react-dom/client/hydrateRoot.md similarity index 92% rename from beta/src/content/apis/react-dom/client/hydrateRoot.md rename to beta/src/content/reference/react-dom/client/hydrateRoot.md index 3fa3833f1..3602159a8 100644 --- a/beta/src/content/apis/react-dom/client/hydrateRoot.md +++ b/beta/src/content/reference/react-dom/client/hydrateRoot.md @@ -4,7 +4,7 @@ title: hydrateRoot -`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 `` 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 ``, 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 ``, 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, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -176,7 +176,7 @@ function Counter() { -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) @@ -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): @@ -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}) { -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. diff --git a/beta/src/content/apis/react-dom/client/index.md b/beta/src/content/reference/react-dom/client/index.md similarity index 65% rename from beta/src/content/apis/react-dom/client/index.md rename to beta/src/content/reference/react-dom/client/index.md index b20b5f435..7e0708cf4 100644 --- a/beta/src/content/apis/react-dom/client/index.md +++ b/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) --- diff --git a/beta/src/content/apis/react-dom/components/common.md b/beta/src/content/reference/react-dom/components/common.md similarity index 97% rename from beta/src/content/apis/react-dom/components/common.md rename to beta/src/content/reference/react-dom/components/common.md index 4a453f40c..3d15f28e2 100644 --- a/beta/src/content/apis/react-dom/components/common.md +++ b/beta/src/content/reference/react-dom/components/common.md @@ -20,15 +20,15 @@ All built-in browser components, such as [`
    `](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 `
    `. +* `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 `
    `. * `dangerouslySetInnerHTML`: An object of the form `{ __html: '

    some html

    ' }` 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 [`