+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js active
+import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js
+import { useState, unstable_ViewTransition as ViewTransition } from "react"; import LikeButton from "./LikeButton"; import { useRouter } from "./router"; import { PauseIcon, PlayIcon } from "./Icons"; import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
+ {/* Custom classes based on transition type. */}
+
+ {heading}
+
+ {isPending && }
+
+
+ {/* Opt-out of ViewTransition for the content. */}
+ {/* Content can define it's own ViewTransition. */}
+
+
+
{children}
+
+
+
+ );
+}
+```
+
+```js src/LikeButton.js hidden
+import {useState} from 'react';
+import {Heart} from './Icons';
+
+// A hack since we don't actually have a backend.
+// Unlike local state, this survives videos being filtered.
+const likedVideos = new Set();
+
+export default function LikeButton({video}) {
+ const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id));
+ const [animate, setAnimate] = useState(false);
+ return (
+
+ );
+}
+```
+
+```js src/Videos.js hidden
+import { useState, unstable_ViewTransition as ViewTransition } from "react";
+import LikeButton from "./LikeButton";
+import { useRouter } from "./router";
+import { PauseIcon, PlayIcon } from "./Icons";
+import { startTransition } from "react";
+
+export function Thumbnail({ video, children }) {
+ // Add a name to animate with a shared element transition.
+ // This uses the default animation, no additional css needed.
+ return (
+
+
@@ -273,11 +273,22 @@ export default function CatFriends() {
}
function setupCatList() {
- const catList = [];
- for (let i = 0; i < 10; i++) {
- catList.push("https://loremflickr.com/320/240/cat?lock=" + i);
+ const catCount = 10;
+ const catList = new Array(catCount)
+ for (let i = 0; i < catCount; i++) {
+ let imageUrl = '';
+ if (i < 5) {
+ imageUrl = "https://placecats.com/neo/320/240";
+ } else if (i < 8) {
+ imageUrl = "https://placecats.com/millie/320/240";
+ } else {
+ imageUrl = "https://placecats.com/bella/320/240";
+ }
+ catList[i] = {
+ id: i,
+ imageUrl,
+ };
}
-
return catList;
}
@@ -309,42 +320,10 @@ li {
}
```
-```json package.json hidden
-{
- "dependencies": {
- "react": "canary",
- "react-dom": "canary",
- "react-scripts": "^5.0.0"
- }
-}
-```
-
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
-
{
- const map = getMap();
- if (node) {
- // Add to the Map
- map.set(cat, node);
- } else {
- // Remove from the Map
- map.delete(cat);
- }
- }}
->
-```
-
-This lets you read individual DOM nodes from the Map later.
-
-
-
-This example shows another approach for managing the Map with a `ref` callback cleanup function.
-
```js
```
-
+This lets you read individual DOM nodes from the Map later.
+
+
+
+When Strict Mode is enabled, ref callbacks will run twice in development.
+
+Read more about [how this helps find bugs](/reference/react/StrictMode#fixing-bugs-found-by-re-running-ref-callbacks-in-development) in callback refs.
+
+
## Accessing another component's DOM nodes {/*accessing-another-components-dom-nodes*/}
-When you put a ref on a built-in component that outputs a browser element like ``, React will set that ref's `current` property to the corresponding DOM node (such as the actual `` in the browser).
+
+Refs are an escape hatch. Manually manipulating _another_ component's DOM nodes can make your code fragile.
+
-However, if you try to put a ref on **your own** component, like ``, by default you will get `null`. Here is an example demonstrating it. Notice how clicking the button **does not** focus the input:
+You can pass refs from parent component to child components [just like any other prop](/learn/passing-props-to-a-component).
-
-
-```js
+```js {3-4,9}
import { useRef } from 'react';
-function MyInput(props) {
- return ;
+function MyInput({ ref }) {
+ return ;
}
-export default function MyForm() {
+function MyForm() {
const inputRef = useRef(null);
-
- function handleClick() {
- inputRef.current.focus();
- }
-
- return (
- <>
-
-
- >
- );
+ return
}
```
-
-
-To help you notice the issue, React also prints an error to the console:
-
-
-
-Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
-
-
-
-This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating _another_ component's DOM nodes makes your code even more fragile.
-
-Instead, components that _want_ to expose their DOM nodes have to **opt in** to that behavior. A component can specify that it "forwards" its ref to one of its children. Here's how `MyInput` can use the `forwardRef` API:
-
-```js
-const MyInput = forwardRef((props, ref) => {
- return ;
-});
-```
-
-This is how it works:
-
-1. `` tells React to put the corresponding DOM node into `inputRef.current`. However, it's up to the `MyInput` component to opt into that--by default, it doesn't.
-2. The `MyInput` component is declared using `forwardRef`. **This opts it into receiving the `inputRef` from above as the second `ref` argument** which is declared after `props`.
-3. `MyInput` itself passes the `ref` it received to the `` inside of it.
+In the above example, a ref is created in the parent component, `MyForm`, and is passed to the child component, `MyInput`. `MyInput` then passes the ref to ``. Because `` is a [built-in component](/reference/react-dom/components/common) React sets the `.current` property of the ref to the `` DOM element.
-Now clicking the button to focus the input works:
+The `inputRef` created in `MyForm` now points to the `` DOM element returned by `MyInput`. A click handler created in `MyForm` can access `inputRef` and call `focus()` to set the focus on ``.
```js
-import { forwardRef, useRef } from 'react';
+import { useRef } from 'react';
-const MyInput = forwardRef((props, ref) => {
- return ;
-});
+function MyInput({ ref }) {
+ return ;
+}
-export default function Form() {
+export default function MyForm() {
const inputRef = useRef(null);
function handleClick() {
@@ -455,24 +406,18 @@ export default function Form() {
-In design systems, it is a common pattern for low-level components like buttons, inputs, and so on, to forward their refs to their DOM nodes. On the other hand, high-level components like forms, lists, or page sections usually won't expose their DOM nodes to avoid accidental dependencies on the DOM structure.
-
#### Exposing a subset of the API with an imperative handle {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/}
-In the above example, `MyInput` exposes the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with `useImperativeHandle`:
+In the above example, the ref passed to `MyInput` is passed on to the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with [`useImperativeHandle`](/reference/react/useImperativeHandle):
```js
-import {
- forwardRef,
- useRef,
- useImperativeHandle
-} from 'react';
+import { useRef, useImperativeHandle } from "react";
-const MyInput = forwardRef((props, ref) => {
+function MyInput({ ref }) {
const realInputRef = useRef(null);
useImperativeHandle(ref, () => ({
// Only expose focus and nothing else
@@ -480,8 +425,8 @@ const MyInput = forwardRef((props, ref) => {
realInputRef.current.focus();
},
}));
- return ;
-});
+ return ;
+};
export default function Form() {
const inputRef = useRef(null);
@@ -493,9 +438,7 @@ export default function Form() {
return (
<>
-
+
>
);
}
@@ -503,7 +446,7 @@ export default function Form() {
-Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, `useImperativeHandle` instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside `useImperativeHandle` call.
+Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, [`useImperativeHandle`](/reference/react/useImperativeHandle) instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside [`useImperativeHandle`](/reference/react/useImperativeHandle) call.
@@ -615,7 +558,7 @@ export default function TodoList() {
const newTodo = { id: nextId++, text: text };
flushSync(() => {
setText('');
- setTodos([ ...todos, newTodo]);
+ setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView({
behavior: 'smooth',
@@ -715,7 +658,7 @@ However, this doesn't mean that you can't do it at all. It requires caution. **Y
- Refs are a generic concept, but most often you'll use them to hold DOM elements.
- You instruct React to put a DOM node into `myRef.current` by passing `
`.
- Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements.
-- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using `forwardRef` and passing the second `ref` argument down to a specific node.
+- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using the `ref` prop.
- Avoid changing DOM nodes managed by React.
- If you do modify DOM nodes managed by React, modify parts that React has no reason to update.
@@ -944,12 +887,30 @@ export default function CatFriends() {
);
}
-const catList = [];
-for (let i = 0; i < 10; i++) {
- catList.push({
+const catCount = 10;
+const catList = new Array(catCount);
+for (let i = 0; i < catCount; i++) {
+ const bucket = Math.floor(Math.random() * catCount) % 2;
+ let imageUrl = '';
+ switch (bucket) {
+ case 0: {
+ imageUrl = "https://placecats.com/neo/250/200";
+ break;
+ }
+ case 1: {
+ imageUrl = "https://placecats.com/millie/250/200";
+ break;
+ }
+ case 2:
+ default: {
+ imageUrl = "https://placecats.com/bella/250/200";
+ break;
+ }
+ }
+ catList[i] = {
id: i,
- imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i
- });
+ imageUrl,
+ };
}
```
@@ -1029,7 +990,7 @@ export default function CatFriends() {
behavior: 'smooth',
block: 'nearest',
inline: 'center'
- });
+ });
}}>
Next
@@ -1061,12 +1022,30 @@ export default function CatFriends() {
);
}
-const catList = [];
-for (let i = 0; i < 10; i++) {
- catList.push({
+const catCount = 10;
+const catList = new Array(catCount);
+for (let i = 0; i < catCount; i++) {
+ const bucket = Math.floor(Math.random() * catCount) % 2;
+ let imageUrl = '';
+ switch (bucket) {
+ case 0: {
+ imageUrl = "https://placecats.com/neo/250/200";
+ break;
+ }
+ case 1: {
+ imageUrl = "https://placecats.com/millie/250/200";
+ break;
+ }
+ case 2:
+ default: {
+ imageUrl = "https://placecats.com/bella/250/200";
+ break;
+ }
+ }
+ catList[i] = {
id: i,
- imageUrl: 'https://loremflickr.com/250/200/cat?lock=' + i
- });
+ imageUrl,
+ };
}
```
@@ -1117,7 +1096,7 @@ Make it so that clicking the "Search" button puts focus into the field. Note tha
-You'll need `forwardRef` to opt into exposing a DOM node from your own component like `SearchInput`.
+You'll need to pass `ref` as a prop to opt into exposing a DOM node from your own component like `SearchInput`.
@@ -1202,18 +1181,14 @@ export default function SearchButton({ onClick }) {
```
```js src/SearchInput.js
-import { forwardRef } from 'react';
-
-export default forwardRef(
- function SearchInput(props, ref) {
- return (
-
- );
- }
-);
+export default function SearchInput({ ref }) {
+ return (
+
+ );
+}
```
```css
diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md
index 1aea87b35..e81678c8e 100644
--- a/src/content/learn/passing-data-deeply-with-context.md
+++ b/src/content/learn/passing-data-deeply-with-context.md
@@ -468,15 +468,15 @@ import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
-
+
{children}
-
+
);
}
```
-This tells React: "if any component inside this `` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it.
+This tells React: "if any component inside this `` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it.
@@ -514,9 +514,9 @@ import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
-
+
{children}
-
+
);
}
@@ -567,7 +567,7 @@ export const LevelContext = createContext(1);
It's the same result as the original code, but you did not need to pass the `level` prop to each `Heading` component! Instead, it "figures out" its heading level by asking the closest `Section` above:
1. You pass a `level` prop to the ``.
-2. `Section` wraps its children into ``.
+2. `Section` wraps its children into ``.
3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`.
## Using and providing context from the same component {/*using-and-providing-context-from-the-same-component*/}
@@ -595,9 +595,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
-
+
{children}
-
+
);
}
@@ -643,9 +643,9 @@ export default function Section({ children }) {
const level = useContext(LevelContext);
return (
-
+
{children}
-
+
);
}
@@ -776,9 +776,9 @@ export default function Section({ children, isFancy }) {
'section ' +
(isFancy ? 'fancy' : '')
}>
-
+
{children}
-
+
);
}
@@ -868,7 +868,7 @@ In general, if some information is needed by distant components in different par
* To pass context:
1. Create and export it with `export const MyContext = createContext(defaultValue)`.
2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep.
- 3. Wrap children into `` to provide it from a parent.
+ 3. Wrap children into `` to provide it from a parent.
* Context passes through any components in the middle.
* Context lets you write components that "adapt to their surroundings".
* Before you use context, try passing props or passing JSX as `children`.
@@ -1022,7 +1022,7 @@ li {
Remove `imageSize` prop from all the components.
-Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`:
+Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`:
@@ -1036,7 +1036,7 @@ export default function App() {
const [isLarge, setIsLarge] = useState(false);
const imageSize = isLarge ? 150 : 100;
return (
-
-
+
)
}
diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md
index d35071845..11d398d23 100644
--- a/src/content/learn/preserving-and-resetting-state.md
+++ b/src/content/learn/preserving-and-resetting-state.md
@@ -672,7 +672,7 @@ label {
-The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `div` to a `section`. When the child `div` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
+The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `section` to a `div`. When the child `section` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well.
@@ -2011,7 +2011,7 @@ export default function ContactList() {