Last updated: Apr 7, 2024
Reading timeยท2 min
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 element = ref.current; console.log(element); // ๐๏ธ element here }, []); return ( <div> <div ref={ref}> <h2>bobbyhadz.com</h2> </div> </div> ); }
The useRef() hook can be passed an initial value as an argument.
const ref = useRef();
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.
const ref = useRef(null);
current
property on the ref object to get access to the div
element on which we set the ref
prop.useEffect(() => { const element = ref.current; console.log(element); // ๐๏ธ element here }, []);
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.
current
property of the ref
in an event handlerYou 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 element = ref.current; console.log(element); // ๐๏ธ element here }, []); const handleClick = () => { console.log(ref.current); // ๐๏ธ element here }; return ( <div> <div ref={ref}> <h2>bobbyhadz.com</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 can access it.
If you use TypeScript, you might get the error useRef "Object is possibly null"