Skip to content

Commit a7bce3f

Browse files
rewrite and move content to useRef reference page
1 parent 8541292 commit a7bce3f

File tree

1 file changed

+114
-91
lines changed

1 file changed

+114
-91
lines changed

src/content/reference/react/useRef.md

Lines changed: 114 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -540,41 +540,96 @@ Here, the `playerRef` itself is nullable. However, you should be able to convinc
540540
541541
### Detect DOM changes with a ref {/*detect-dom-changes-with-a-ref*/}
542542
543-
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.
543+
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).
544+
545+
```js {5,10}
546+
import { useRef, useCallback } from "react";
547+
548+
function Logo() {
549+
const logoRef = useRef(null);
550+
const setLogoRef = useCallback((node) => {
551+
logoRef.current = node;
552+
//...
553+
}, []);
554+
//...
555+
return <div ref={setLogoRef}></div>
556+
}
557+
```
558+
559+
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.
560+
561+
```js {7-13}
562+
import { useRef, useCallback } from "react";
563+
564+
function Logo() {
565+
const logoRef = useRef(null);
566+
const setLogoRef = useCallback((node) => {
567+
logoRef.current = node;
568+
const observer = new MutationObserver(() => {
569+
if (node && node.children.length > 0) {
570+
// TODO: handle when children are added to this DOM node
571+
observer.disconnect();
572+
}
573+
});
574+
observer.observe(node, { childList: true });
575+
}, []);
576+
//...
577+
return <div ref={setLogoRef}></div>
578+
}
579+
```
580+
581+
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).
582+
583+
```js {10-13}
584+
import { useRef, useCallback } from "react";
585+
586+
function Logo() {
587+
const logoRef = useRef(null);
588+
const setLogoRef = useCallback((node) => {
589+
logoRef.current = node;
590+
const observer = new MutationObserver(() => { /*...*/ });
591+
observer.observe(node, { /*...*/ });
592+
593+
return () => {
594+
logoRef.current = null;
595+
observer.disconnect();
596+
};
597+
}, []);
598+
//...
599+
return <div ref={setLogoRef}></div>
600+
}
601+
```
602+
603+
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.
544604
545605
<Sandpack>
546606
547607
```js src/App.js active
548608
import { useState, useRef, useCallback } from "react";
549-
import { useDrawReactLogo } from "./draw-logo";
609+
import { useDrawLogo } from "./draw-logo";
550610

551-
export default function ReactLogo() {
611+
export default function Logo() {
552612
const [loading, setLoading] = useState(true);
553613
const logoRef = useRef(null);
554-
// the ref callback function should be wraped in
555-
// useCallback so the listener doesn't reconnect
556-
// on each render
614+
// useCallback prevents reconnections on each render
557615
const setLogoRef = useCallback((node) => {
558616
logoRef.current = node;
559617
const observer = new MutationObserver(() => {
560618
if (node && node.children.length > 0) {
561619
setLoading(false);
562-
logoRef.current = null;
563620
observer.disconnect();
564621
}
565622
});
566623
observer.observe(node, { childList: true });
567624

568625
return () => {
569-
// When defining a ref callback cleanup function
570-
// it is important to re-assign the ref object
571-
// to null so that other references will not
572-
// point to the ghost element that no longer exists
626+
// Explicitly setting the ref to null in cleanup
627+
// prevents refs to unmounted DOM nodes
573628
logoRef.current = null;
574629
observer.disconnect();
575630
};
576631
}, []);
577-
useDrawReactLogo(logoRef);
632+
useDrawLogo(logoRef);
578633

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

591-
export function useDrawReactLogo(chartRef) {
592-
// Use a ref to that status of if drawing
646+
export function useDrawLogo(ref) {
647+
// Use a ref to store the status of if drawing
593648
// has started or not outside of render
594649
const drawnRef = useRef(false);
595650
useEffect(() => {
596651
if (!drawnRef.current) {
597-
delayedDrawReactLogo(chartRef.current);
652+
delayedDrawLogo(ref.current);
598653
drawnRef.current = true;
599654
}
600-
}, [chartRef]);
655+
}, [ref]);
601656
}
602657

603-
function delayedDrawReactLogo(node) {
658+
function delayedDrawLogo(node) {
604659
// add 500ms delay to simulate
605660
// a long drawing time
606-
setTimeout(() => drawReactLogo(node), 500);
661+
setTimeout(() => drawLogo(node), 500);
607662
}
608663

609-
function drawReactLogo(node) {
664+
function drawLogo(node) {
610665
const svgNamespace = "http://www.w3.org/2000/svg";
611666
const createSvgElement = (type, attributes) => {
612667
const element = document.createElementNS(svgNamespace, type);
@@ -649,12 +704,14 @@ function drawReactLogo(node) {
649704
650705
<DeepDive>
651706
652-
#### Prevent reconnections with useCallback {/*prevent-listener-reconnections-with-usecallback*/}
707+
#### How to avoid callback reconnections with useCallback {/*how-to-avoid-callback-reconnections-with-usecallback*/}
653708
654-
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.
709+
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.
655710
656-
```js
711+
```js {4}
657712
export default function ReactLogo() {
713+
// 🚩 without useCallback, the callback changes every
714+
// render, which causes the listener to reconnect
658715
const setLogoRef = (node) => {
659716
//...
660717
};
@@ -663,10 +720,14 @@ export default function ReactLogo() {
663720
}
664721
```
665722
666-
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.
723+
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.
724+
725+
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.
667726
668-
```js {2,4}
727+
```js {4,6}
669728
export default function ReactLogo() {
729+
// ✅ with useCallback, the callback is stable
730+
// so the listener doesn't reconnect each render
670731
const setLogoRef = useCallback((node) => {
671732
//....
672733
}, []);
@@ -679,89 +740,51 @@ export default function ReactLogo() {
679740
680741
<DeepDive>
681742
682-
#### Avoiding Stale Refs {/*avoiding-stale-refs*/}
743+
#### How to avoid a ref to a unmounted node {/*how-to-avoid-a-ref-to-a-unmounted-node*/}
683744
684-
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.
685-
686-
<Sandpack>
745+
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.
687746
688747
```js
689-
import { useRef, useState } from "react";
748+
export default function Logo() {
749+
const logoRef = useRef(null);
750+
const setLogoRef = useCallback((node) => {
751+
logoRef.current = node;
752+
//...
690753

691-
export default function MyForm() {
692-
const [showInput, setShowInput] = useState(true);
693-
const inputRef = useRef();
694-
const handleCheckboxChange = (event) => {
695-
setShowInput(event.target.checked);
696-
};
697-
const handleSubmit = (event) => {
698-
event.preventDefault();
699-
if (inputRef.current) {
700-
alert(`Input value is: "${inputRef.current.value}"`);
701-
} else {
702-
alert("no input");
703-
}
704-
};
705-
const inputRefCallback = (node) => {
706-
inputRef.current = node;
754+
// 🚩 if your ref cleanup function does not explicitly
755+
// set the ref to null the ref may point to a
756+
// unmounted DOM node
707757
return () => {
708-
// ⚠️ You must set `ref.current` to `null`
709-
// in this cleanup function e.g.
710-
// `inputRef.current = null;`
711-
// to prevent hanging refs to unmounted DOM nodes
758+
observer.disconnect();
712759
};
713-
};
714-
715-
return (
716-
<form onSubmit={handleSubmit}>
717-
<div>
718-
<label>
719-
<input
720-
type="checkbox"
721-
checked={showInput}
722-
onChange={handleCheckboxChange}
723-
/>
724-
Show Input
725-
</label>
726-
</div>
727-
{showInput && (
728-
<div>
729-
<label>
730-
Input:
731-
<input
732-
type="text"
733-
defaultValue="value from input DOM node"
734-
ref={inputRefCallback}
735-
/>
736-
</label>
737-
</div>
738-
)}
739-
<button type="submit">Submit</button>
740-
</form>
741-
);
760+
}, []);
761+
//...
762+
return <div ref={setLogoRef}></div>
742763
}
743764
```
744765
745-
</Sandpack>
746-
747766
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.
748767
749-
```js
750-
import { useRef } from "react";
768+
```js {11}
769+
export default function Logo() {
770+
const logoRef = useRef(null);
771+
const setLogoRef = useCallback((node) => {
772+
logoRef.current = node;
773+
//...
751774

752-
function MyInput() {
753-
const inputRef = useRef()
754-
const inputRefCallback = (node) => {
755-
inputRef.current = node;
756775
return () => {
757-
// ⚠️ You must set `ref.current` to `null` in this cleanup
758-
// function to prevent hanging refs to unmounted DOM nodes
759-
inputRef.current = null;
776+
// ✅ Explicitly setting the ref to null in the
777+
// cleanup function prevents references to
778+
// unmounted DOM nodes
779+
logoRef.current = null;
780+
observer.disconnect();
760781
};
761-
};
762-
return <input ref={inputRefCallback}>
782+
}, []);
783+
//...
784+
return <div ref={setLogoRef}></div>
763785
}
764786
```
787+
765788
</DeepDive>
766789
767790
---

0 commit comments

Comments
 (0)