React Hooks: useRef
1. Introduction
The useRef
hook is a part of React’s Hooks API, introduced in React 16.8. It allows you to create mutable object references that persist for the full lifetime of the component.
2. Definition
useRef
returns a mutable ref object whose .current
property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
Key characteristics of useRef
:
- It is primarily used to access DOM elements directly.
- It does not cause re-renders when the
.current
property is changed. - It can hold any mutable value similar to instance fields in class components.
3. Usage
To use useRef
, you need to import it from React:
import React, { useRef } from 'react';
Example 1: Accessing a DOM Element
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
);
}
Example 2: Storing a Mutable Value
function Timer() {
const count = useRef(0);
useEffect(() => {
const interval = setInterval(() => {
count.current += 1;
console.log(count.current);
}, 1000);
return () => clearInterval(interval);
}, []);
return Check console for count updates!;
}
4. Best Practices
To effectively use useRef
, consider the following best practices:
- Only use
useRef
for non-visual state or when you specifically need to access a DOM node. - Be cautious about using
useRef
for values that affect rendering. Instead, use state hooks in such cases. - Combine
useRef
withuseEffect
when you need to trigger side effects based on DOM updates.
5. FAQ
What is the difference between useRef and useState?
useRef
does not cause re-renders when its value changes, while useState
does.
Can I use useRef to store objects or arrays?
Yes, useRef
can hold any mutable value, including objects and arrays.
When should I use useRef?
Use useRef
when you need to access a DOM node directly or when you want to keep a mutable value that does not trigger a re-render.