Lesson 21 of 30
70%
useRef
useRef holds a value that lasts across renders without causing a render when it changes.
The usual use is a box that points at a DOM node.
Focus an input
javascript
ref={inputRef} tells React to put the DOM node on inputRef.current after paint.
current is null on the first render, before the node exists.
A mutable box
You can also store a timer id or the previous value.
Changing .current does not re-render. That is the difference from useState.
javascript
When not to use ref
If the screen should update, use state.
If you are reaching into the DOM to set textContent, you are fighting React. Render the text instead.
Tip: ref is an escape hatch. Use it for focus, scroll, media players, and values that are not UI.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.