In react a common pattern is to use state variables to maintain state and then change UI based on the state. Rarely one has to use the hook useRef, but it is something that everyone planning to use react must really know.
What exactly is useRef?
The useRef
hook in React is a versatile tool that allows you to:
Store Mutable Values: It creates a container that holds a value, and that value can be changed without triggering a re-render of your component. This is incredibly useful for things like storing timer intervals, tracking input values before submission, and more.
Access DOM Elements Directly:
useRef
can be used to create references to specific elements in your React components' structure (the virtual DOM). This can be helpful for tasks like focusing on an input field or measuring the dimensions of an element. This is the most common usecase for useRef.
Three features of useRef
Persistence: The value stored in a ref persists throughout the entire lifetime of the component. Component re-renders won't reset or change the value in the ref.
No Re-renders: Unlike state updates, changing the value of a ref does not cause the component to re-render.
Mutable: The
current
property of the ref object is mutable, meaning you can change its value directly.
Common Scenarios for useRef
Let's look at some practical use cases where useRef
shines:
Handling Focus on Input Elements: Use
useRef
to reference an input element and then programmatically place the cursor focus on it when needed.Storing Timer IDs: When working with functions like
setInterval
, a ref can store the timer ID, allowing you to clear the timer (e.g., withclearInterval
) when the component unmounts.Prior Value Tracking: Need to keep track of the previous value of a prop or state? Use
useRef
to store the old value and compare it to the updated one.Accessing DOM Measurements: If you need to know the width or position of an element on the screen,
useRef
can get the job done.
Code Example
Let's create a simple example demonstrating how to use useRef
to focus an input field:
import React, { useRef, useEffect } from 'react';
function MyComponent() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // Focus on render
}, []);
return (
<div>
<input type="text" ref={inputRef} />
</div>
);
}
Important Notes
Overusing
useRef
can sometimes indicate a need to re-think your component structure. If you find yourself reaching foruseRef
too frequently, consider whether restructuring your components with state and props could be a better design choice.As with any tool, use
useRef
judiciously. It's a powerful hook that fills a very specific need within the world of React state management.
As a front end engineer I will always recommend against avoiding useRef if you can use something else.