From f6871579df23b831b315727eeff335f3c174043b Mon Sep 17 00:00:00 2001 From: Jack Pope Date: Tue, 23 Apr 2024 10:51:24 -0400 Subject: [PATCH 1/2] Add documentation for ref cleanup functions --- .../learn/manipulating-the-dom-with-refs.md | 97 +++++++++++-------- .../reference/react-dom/components/common.md | 12 ++- 2 files changed, 65 insertions(+), 44 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index bc9a3eac472..8276705c702 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -211,25 +211,26 @@ 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.](/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. +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 call your cleanup function 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: ```js -import { useRef } from 'react'; +import { useRef, useState } from "react"; export default function CatFriends() { const itemsRef = useRef(null); + const [catList, setCatList] = useState(setupCatList); - function scrollToId(itemId) { + function scrollToCat(cat) { const map = getMap(); - const node = map.get(itemId); + const node = map.get(cat); node.scrollIntoView({ - behavior: 'smooth', - block: 'nearest', - inline: 'center' + behavior: "smooth", + block: "nearest", + inline: "center", }); } @@ -241,37 +242,38 @@ export default function CatFriends() { return itemsRef.current; } + async function addCat() { + setCatList((prev) => [createCatImg(prev.length + 100), ...prev]); + } + + async function removeCat() { + setCatList((prev) => prev.slice(1)); + } + return ( <>
    - {catList.map(cat => ( + {catList.map((cat) => (
  • { const map = getMap(); - if (node) { - map.set(cat.id, node); - } else { - map.delete(cat.id); - } + map.set(cat, node); + + return () => { + map.delete(cat); + }; }} > - {'Cat +
  • ))}
@@ -280,12 +282,17 @@ export default function CatFriends() { ); } -const catList = []; -for (let i = 0; i < 10; i++) { - catList.push({ - id: i, - imageUrl: 'https://placekitten.com/250/200?image=' + i - }); +function setupCatList() { + const catList = []; + for (let i = 0; i < 10; i++) { + catList.push(createCatImg(i)); + } + + return catList; +} + +function createCatImg(i) { + return "https://loremflickr.com/320/240/cat?lock=" + i; } ``` @@ -316,6 +323,16 @@ 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: @@ -325,13 +342,13 @@ In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a key={cat.id} ref={node => { const map = getMap(); - if (node) { - // Add to the Map - map.set(cat.id, node); - } else { - // Remove from the Map - map.delete(cat.id); - } + // Add to the map + map.set(cat, node); + + return () => { + // Remove from the map + map.delete(cat); + }; }} > ``` diff --git a/src/content/reference/react-dom/components/common.md b/src/content/reference/react-dom/components/common.md index 610742735a3..f44cd0a01b9 100644 --- a/src/content/reference/react-dom/components/common.md +++ b/src/content/reference/react-dom/components/common.md @@ -251,17 +251,21 @@ Instead of a ref object (like the one returned by [`useRef`](/reference/react/us [See an example of using the `ref` callback.](/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback) -When the `
` DOM node is added to the screen, React will call your `ref` callback with the DOM `node` as the argument. When that `
` DOM node is removed, React will call your `ref` callback with `null`. +When the `
` DOM node is added to the screen, React will call your `ref` callback with the DOM `node` as the argument. If a cleanup function is returned, React will call it when that `
` DOM node is removed. Without a cleanup function, React will call your `ref` callback again with `null` when the node is removed. -React will also call your `ref` callback whenever you pass a *different* `ref` callback. In the above example, `(node) => { ... }` is a different function on every render. When your component re-renders, the *previous* function will be called with `null` as the argument, and the *next* function will be called with the DOM node. +React will also call your `ref` callback whenever you pass a *different* `ref` callback. In the above example, `(node) => { ... }` is a different function on every render. When your component re-renders, React will call the *previous* callback's cleanup function if provided. If not cleanup function is defined, the `ref` callback will be called with `null` as the argument. The *next* function will be called with the DOM node. #### Parameters {/*ref-callback-parameters*/} -* `node`: A DOM node or `null`. React will pass you the DOM node when the ref gets attached, and `null` when the ref gets detached. Unless you pass the same function reference for the `ref` callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component. +* `node`: A DOM node or `null`. React will pass you the DOM node when the ref gets attached, and `null` when the `ref` gets detached if no cleanup function is returned. Unless you pass the same function reference for the `ref` callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component. #### Returns {/*returns*/} -Do not return anything from the `ref` callback. +* **optional** `cleanup function`: When the `ref` is detached, React will call the cleanup function. If a function is not returned by the `ref` callback, React will call the callback again with `null` as the argument when the `ref` gets detached. + +#### Caveats {/*caveats*/} + +* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, implement the cleanup function. --- From 28220b76fa0d7cbee2f72d89cd35fc8f28af9e03 Mon Sep 17 00:00:00 2001 From: Jack Pope Date: Wed, 24 Apr 2024 11:34:41 -0400 Subject: [PATCH 2/2] Contain changes within canary block --- .../learn/manipulating-the-dom-with-refs.md | 52 +++++++++++-------- .../reference/react-dom/components/common.md | 27 ++++++++-- 2 files changed, 52 insertions(+), 27 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 8276705c702..2d44d735359 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/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.](/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 call your cleanup function 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: @@ -242,19 +242,9 @@ export default function CatFriends() { return itemsRef.current; } - async function addCat() { - setCatList((prev) => [createCatImg(prev.length + 100), ...prev]); - } - - async function removeCat() { - setCatList((prev) => prev.slice(1)); - } - return ( <>