Today, I’m continuing to do a deep dive on the various React Hooks by taking notes while reading through useRef.
Main purpose of useRef: reference a value that’s not needed for rendering
- Returns object with single property
current
- Even if
ref.current
value changes -> re-render is not triggered. To React, ref is a plain JS object. - Do not write or read
ref.current
during rendering (what does this mean?) except for initialization - Store info that doesn’t affect the visual output of the component BUT should not be reset between re-renders
What does it mean when you should not write or read ref
during rendering (except during initialization)?
- Basically, avoid modifying the value of a
useRef
object within the body of the component during the rendering process. - Instead, in general, read or write refs within event handlers or effects
- One clarification that I learned: useEffect runs AFTER the render of a component (after the DOM has been updated)
Manipulating the DOM with a ref - Steps
- Declare a ref object with initial value of
null
import { useRef } from 'react';
function Component() {
const divRef = useRef(null);
// ....
}
- Pass your ref object as
ref
attribute to the JSX of the DOM node you want to manipulate:
//...
return ( <div ref={divRef}> </div>)
- Upon DOM node creation and rendering - React sets the
current
property of your ref object to that assigned DOM node. - To access the particular DOM node of the corresponding ref object, you can use methods like
focus()
.
function grabDiv() {
divRef.current.focus()
}
Next up:
- Reading the reference docs on
useState
, and thenuseReducer
- Read React.dev’s Section on [Escape Hatches]