TIL - React callback refs
For a side-project of mine I want to have rich-text editing capabilities in my app. I've written my fair share of React code, but seeing the following code in the nytimes/react-prosemirror package still surprised me:
1import { EditorState } from "prosemirror-state";
2import { ProseMirror } from "@nytimes/react-prosemirror";
3
4export function ProseMirrorEditor() {
5 const [mount, setMount] = useState(null);
6
7 return (
8 <ProseMirror
9 mount={mount}
10 defaultState={EditorState.create({ schema })}
11 >
12 <div ref={setMount} />
13 </ProseMirror>
14 );
15}
It might be totally obvious to you, but to me, seeing that ref={setMount} property didn't make sense. Turns out, that react-dom supports passing functions to an elements ref property, which will get called with the element as its argument when the element gets mounted and with null when it unmounts.
Of course, I'm not the first to stumble over this feature. Here's is one in-depth post about this topic: React ref Callback Use Cases by Jules Blom
Since Jules does a great job at explaining this topic I won't try to explain it myself here. So just go read the post and be enlightened.
Further reading:
- Jules Blom - React ref Callback Use Cases
- jjenzz - Compound Components
- Kent C. Dodds - React Hooks: Compound Components
- jjenzz - Avoid Global State — Co-locate with Uncontrolled Compound Components
- jjenzz - Smarter, Dumb Breadcrumb
- Vladimir Klepov as a Coder - So you think you know everything about React refs