Borislav Hadzhiev
Thu Apr 28 2022·2 min read
Photo by Gabriel
A React ref
most commonly returns undefined
or null
when we try to
access its current
property before its corresponding DOM element is rendered.
To get around this, access the ref in the useEffect
hook or when an event is
triggered.
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // 👈️ undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // 👈️ element here }, []); return ( <div> <div ref={ref}> <h2>Hello</h2> </div> </div> ); }
The useRef() hook can be
passed an initial value as an argument. The hook returns a mutable ref object
whose .current
property is initialized to the passed argument.
We didn't pass an initial value to useRef
so its current
property is set to
undefined
.
If we had passed null
to the hook, its current
property would be null
if
accessed immediately.
current
property on the ref object to get access to the div
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
useEffect
hook because we want to make sure the ref
has been set on the element and the element has been rendered to the DOM.If we try to access the current
property of the ref
directly in the
component, we would get undefined
back because the ref hasn't been set up and
the div
element has not been rendered.
You can also access the current
property of the ref
in an event handler
function.
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // 👈️ undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // 👈️ element here }, []); const handleClick = () => { console.log(ref.current); // 👈️ element here }; return ( <div> <div ref={ref}> <h2>Hello</h2> </div> <button onClick={handleClick}>Click</button> </div> ); }
By the time the user clicks on the button, the ref has been set up and the corresponding element has been rendered to the DOM, so we are able to access it.