useRef Hook
The useRef hook in React is a powerful tool that allows you to create a reference to a DOM node or a value that persists across re-renders. This hook is essential when you need to access a DOM element directly or store a value that should not be re-created on every render. With React 19, the useRef hook has become even more versatile, enabling you to handle complex scenarios with ease.
Basic Example
To start using useRef, you first import it from the react library. Then, you can create a reference and assign it to a DOM element using the ref attribute. Here’s a simple example where we focus an input field when a button is clicked:
import { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}In this example, inputRef is created with useRef(null), and then assigned to the input element. When the button is clicked, the handleFocus function is called, which focuses the input field using inputRef.current.focus().
Advanced Usage
For more advanced scenarios, you might need to use useRef with other hooks, like useEffect, to manage side effects or handle complex state changes. Here’s an example that combines useRef with useEffect to log the width of a div whenever the component mounts or updates:
import { useRef, useEffect } from 'react';
function LogDivWidth() {
const divRef = useRef(null);
useEffect(() => {
if (divRef.current) {
console.log(divRef.current.offsetWidth);
}
}, []);
return <div ref={divRef} style={{ width: '100%', height: '200px' }} />;
}In this example, useEffect is used to log the width of the div to the console when the component mounts. The dependency array is empty ([]), meaning the effect only runs once, when the component mounts.
Best Practices
When using useRef, keep the following best practices in mind:
- Initialize with null: It’s a good practice to initialize your refs with
nullto avoid potential issues with thecurrentproperty. - Use with DOM elements:
useRefis particularly useful when working directly with DOM elements, such as focusing an input or accessing a canvas element. - Combine with other hooks: For more complex logic, consider combining
useRefwith other hooks likeuseStateoruseEffect. - Avoid storing complex state: While
useRefcan store any type of value, it’s generally better to useuseStatefor managing state that affects rendering, and reserveuseReffor values that don’t trigger re-renders.
Key Takeaways
- Persistence across re-renders:
useRefcreates a reference that persists across component re-renders. - Direct DOM access: It’s useful for directly accessing DOM nodes or storing values that don’t trigger re-renders.
- Combination with other hooks:
useRefcan be effectively combined with other React hooks to manage complex component logic. - Best for non-state values: It’s ideal for storing values that don’t affect the component’s rendering state, such as DOM references or timer IDs.