Skip to content

Commit

Permalink
rewrite and move content to useRef reference page
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcarrollcode committed Dec 23, 2024
1 parent 8541292 commit a7bce3f
Showing 1 changed file with 114 additions and 91 deletions.
205 changes: 114 additions & 91 deletions src/content/reference/react/useRef.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,41 +540,96 @@ Here, the `playerRef` itself is nullable. However, you should be able to convinc
### Detect DOM changes with a ref {/*detect-dom-changes-with-a-ref*/}
In some scenarios, you might need to detect changes in the DOM, such as when a component's children are dynamically updated. You can achieve this by using a `ref` callback wrapped in `useCallback` to create a MutationObserver. This approach allows you to observe changes in the DOM and perform actions based on those changes.
In some situations, you might need to detect changes in the DOM, such as when a 3rd party library draws visualizations directly to the DOM. To do so, first create a ref callback: a function passed to the ref attribute of the DOM node you want to observe. The ref callback takes a single argument: the DOM node you'd like to observe. Wrap your ref callback in `useCallback` to [prevent unnecessary reconnections](#how-to-avoid-callback-reconnections-with-usecallback).
```js {5,10}
import { useRef, useCallback } from "react";

function Logo() {
const logoRef = useRef(null);
const setLogoRef = useCallback((node) => {
logoRef.current = node;
//...
}, []);
//...
return <div ref={setLogoRef}></div>
}
```
Next, set up a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to monitor changes and handle those changes accordingly in your ref callback. In this example, the MutationObserver is monitoring for changes to the children of a `<div>`. Don't forget to disconnect your observer when you no longer need to monitor for changes.
```js {7-13}
import { useRef, useCallback } from "react";

function Logo() {
const logoRef = useRef(null);
const setLogoRef = useCallback((node) => {
logoRef.current = node;
const observer = new MutationObserver(() => {
if (node && node.children.length > 0) {
// TODO: handle when children are added to this DOM node
observer.disconnect();
}
});
observer.observe(node, { childList: true });
}, []);
//...
return <div ref={setLogoRef}></div>
}
```
Lastly, you'll need to return a function from your ref callback to cleanup the observer and ref. Explicitly setting the ref to null during cleanup prevents [refs to unmounted DOM nodes](#how-to-avoid-a-ref-to-a-unmounted-node).
```js {10-13}
import { useRef, useCallback } from "react";

function Logo() {
const logoRef = useRef(null);
const setLogoRef = useCallback((node) => {
logoRef.current = node;
const observer = new MutationObserver(() => { /*...*/ });
observer.observe(node, { /*...*/ });

return () => {
logoRef.current = null;
observer.disconnect();
};
}, []);
//...
return <div ref={setLogoRef}></div>
}
```
In this example, the `Logo` component utilizes a `MutationObserver` to detect when child elements are added to a `<div>` allowing it to update the component's state and stop displaying a loading indicator once the logo is fully drawn. Tap the "Reset" button in the upper right corner of the CodeSandbox example below to see how the loading indicator is replaced by the logo.
<Sandpack>
```js src/App.js active
import { useState, useRef, useCallback } from "react";
import { useDrawReactLogo } from "./draw-logo";
import { useDrawLogo } from "./draw-logo";

export default function ReactLogo() {
export default function Logo() {
const [loading, setLoading] = useState(true);
const logoRef = useRef(null);
// the ref callback function should be wraped in
// useCallback so the listener doesn't reconnect
// on each render
// useCallback prevents reconnections on each render
const setLogoRef = useCallback((node) => {
logoRef.current = node;
const observer = new MutationObserver(() => {
if (node && node.children.length > 0) {
setLoading(false);
logoRef.current = null;
observer.disconnect();
}
});
observer.observe(node, { childList: true });

return () => {
// When defining a ref callback cleanup function
// it is important to re-assign the ref object
// to null so that other references will not
// point to the ghost element that no longer exists
// Explicitly setting the ref to null in cleanup
// prevents refs to unmounted DOM nodes
logoRef.current = null;
observer.disconnect();
};
}, []);
useDrawReactLogo(logoRef);
useDrawLogo(logoRef);

return (
<div>
Expand All @@ -588,25 +643,25 @@ export default function ReactLogo() {
```js src/draw-logo.js hidden
import { useRef, useEffect } from "react";

export function useDrawReactLogo(chartRef) {
// Use a ref to that status of if drawing
export function useDrawLogo(ref) {
// Use a ref to store the status of if drawing
// has started or not outside of render
const drawnRef = useRef(false);
useEffect(() => {
if (!drawnRef.current) {
delayedDrawReactLogo(chartRef.current);
delayedDrawLogo(ref.current);
drawnRef.current = true;
}
}, [chartRef]);
}, [ref]);
}

function delayedDrawReactLogo(node) {
function delayedDrawLogo(node) {
// add 500ms delay to simulate
// a long drawing time
setTimeout(() => drawReactLogo(node), 500);
setTimeout(() => drawLogo(node), 500);
}

function drawReactLogo(node) {
function drawLogo(node) {
const svgNamespace = "http://www.w3.org/2000/svg";
const createSvgElement = (type, attributes) => {
const element = document.createElementNS(svgNamespace, type);
Expand Down Expand Up @@ -649,12 +704,14 @@ function drawReactLogo(node) {
<DeepDive>
#### Prevent reconnections with useCallback {/*prevent-listener-reconnections-with-usecallback*/}
#### How to avoid callback reconnections with useCallback {/*how-to-avoid-callback-reconnections-with-usecallback*/}
When a ref callback function change, React will disconnect and reconnect on render. This is similar to a function dependency in an effect. React does this because new prop values may be needed to be passed to the ref callback function.
When React re-renders a component, all the functions defined in the component are recreated. This includes ref callback functions defined in components. When a ref callback function is changed or recreated, React will disconnect and reconnect your ref callback function. React does this because new prop values may need to be passed to the ref callback function. This is similar to a function dependency in an effect.
```js
```js {4}
export default function ReactLogo() {
// 🚩 without useCallback, the callback changes every
// render, which causes the listener to reconnect
const setLogoRef = (node) => {
//...
};
Expand All @@ -663,10 +720,14 @@ export default function ReactLogo() {
}
```
To avoid unnecessary reconnections wrap your ref callback function in [useCallback](/reference/react/useCallback). Make sure to add any dependancies to the `useCallback` dependency array. This will ensure the ref callback is called with updated props when necessary.
To disconnect, React will call your ref callback function with `null` as an argument. To reconnect, React calls your ref callback function with the DOM node as an argument.
To avoid unnecessary disconnections and reconnections wrap your ref callback function in [useCallback](/reference/react/useCallback). Make sure to add any dependencies to the `useCallback` dependency array. This will ensure the ref callback is called with updated props when necessary.
```js {2,4}
```js {4,6}
export default function ReactLogo() {
// ✅ with useCallback, the callback is stable
// so the listener doesn't reconnect each render
const setLogoRef = useCallback((node) => {
//....
}, []);
Expand All @@ -679,89 +740,51 @@ export default function ReactLogo() {
<DeepDive>
#### Avoiding Stale Refs {/*avoiding-stale-refs*/}
#### How to avoid a ref to a unmounted node {/*how-to-avoid-a-ref-to-a-unmounted-node*/}
A `ref` callback function with a cleanup function that does not set `ref.current` to `null` can result in a `ref` to a unmounted node. Uncheck "Show Input" below and click "Submit" to see how the `ref` to the unmounted `<input>` is still accessible by the click handler for the form.
<Sandpack>
A `ref` callback function with a cleanup function that does not set `ref.current` to `null` can result in a `ref` to a unmounted node.
```js
import { useRef, useState } from "react";
export default function Logo() {
const logoRef = useRef(null);
const setLogoRef = useCallback((node) => {
logoRef.current = node;
//...

export default function MyForm() {
const [showInput, setShowInput] = useState(true);
const inputRef = useRef();
const handleCheckboxChange = (event) => {
setShowInput(event.target.checked);
};
const handleSubmit = (event) => {
event.preventDefault();
if (inputRef.current) {
alert(`Input value is: "${inputRef.current.value}"`);
} else {
alert("no input");
}
};
const inputRefCallback = (node) => {
inputRef.current = node;
// 🚩 if your ref cleanup function does not explicitly
// set the ref to null the ref may point to a
// unmounted DOM node
return () => {
// ⚠️ You must set `ref.current` to `null`
// in this cleanup function e.g.
// `inputRef.current = null;`
// to prevent hanging refs to unmounted DOM nodes
observer.disconnect();
};
};

return (
<form onSubmit={handleSubmit}>
<div>
<label>
<input
type="checkbox"
checked={showInput}
onChange={handleCheckboxChange}
/>
Show Input
</label>
</div>
{showInput && (
<div>
<label>
Input:
<input
type="text"
defaultValue="value from input DOM node"
ref={inputRefCallback}
/>
</label>
</div>
)}
<button type="submit">Submit</button>
</form>
);
}, []);
//...
return <div ref={setLogoRef}></div>
}
```
</Sandpack>
To fix the hanging ref to the DOM node that is no longer rendered, set `ref.current` to `null` in the `ref` callback cleanup function.
```js
import { useRef } from "react";
```js {11}
export default function Logo() {
const logoRef = useRef(null);
const setLogoRef = useCallback((node) => {
logoRef.current = node;
//...

function MyInput() {
const inputRef = useRef()
const inputRefCallback = (node) => {
inputRef.current = node;
return () => {
// ⚠️ You must set `ref.current` to `null` in this cleanup
// function to prevent hanging refs to unmounted DOM nodes
inputRef.current = null;
// ✅ Explicitly setting the ref to null in the
// cleanup function prevents references to
// unmounted DOM nodes
logoRef.current = null;
observer.disconnect();
};
};
return <input ref={inputRefCallback}>
}, []);
//...
return <div ref={setLogoRef}></div>
}
```
</DeepDive>
---
Expand Down

0 comments on commit a7bce3f

Please sign in to comment.