Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for ref cleanup functions #6770

Merged
merged 2 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 57 additions & 40 deletions src/content/learn/manipulating-the-dom-with-refs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

<Sandpack>

```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",
});
}

Expand All @@ -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 (
<>
<nav>
<button onClick={() => scrollToId(0)}>
Tom
</button>
<button onClick={() => scrollToId(5)}>
Maru
</button>
<button onClick={() => scrollToId(9)}>
Jellylorum
</button>
<button onClick={addCat}>Add Cat</button>
<button onClick={removeCat}>Remove Cat</button>
<button onClick={() => scrollToCat(catList[0])}>Tom</button>
<button onClick={() => scrollToCat(catList[5])}>Maru</button>
<button onClick={() => scrollToCat(catList[9])}>Jellylorum</button>
</nav>
<div>
<ul>
{catList.map(cat => (
{catList.map((cat) => (
<li
key={cat.id}
key={cat}
ref={(node) => {
const map = getMap();
if (node) {
map.set(cat.id, node);
} else {
map.delete(cat.id);
}
map.set(cat, node);

return () => {
map.delete(cat);
};
}}
>
<img
src={cat.imageUrl}
alt={'Cat #' + cat.id}
/>
<img src={cat} />
</li>
))}
</ul>
Expand All @@ -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;
}

```
Expand Down Expand Up @@ -316,6 +323,16 @@ li {
}
```

```json package.json hidden
{
"dependencies": {
"react": "canary",
"react-dom": "canary",
"react-scripts": "^5.0.0"
}
}
```

</Sandpack>

In this example, `itemsRef` doesn't hold a single DOM node. Instead, it holds a [Map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) from item ID to a DOM node. ([Refs can hold any values!](/learn/referencing-values-with-refs)) The [`ref` callback](/reference/react-dom/components/common#ref-callback) on every list item takes care to update the Map:
Expand All @@ -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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't indicate canary? I also don't understand why we'd need to add/remove cats?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the Canary thing, I would keep the example the same and add a block.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah thanks I missed this spot. Updating to a Canary block.

For the add/remove, this was to make it more obvious how/when the cleanups are fired if you want to extend the example with logs or other behavior. Was helpful when putting it together but I'll update to simplify here.

map.set(cat, node);

return () => {
// Remove from the map
map.delete(cat);
};
}}
>
```
Expand Down
12 changes: 8 additions & 4 deletions src/content/reference/react-dom/components/common.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<div>` DOM node is added to the screen, React will call your `ref` callback with the DOM `node` as the argument. When that `<div>` DOM node is removed, React will call your `ref` callback with `null`.
When the `<div>` 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 `<div>` 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.
* <CanaryBadge title="This feature is only available in the Canary channel" /> **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*/}

* <CanaryBadge title="This feature is only available in the Canary channel" /> 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.

---

Expand Down
Loading