What Is useRef?
useRef is a Hook that lets you reference a value that persists across React re-renders.
This description of useRef is based on the official React documentation, but what does it actually mean? Simply put, I think of useRef as useState without triggering re-renders. React keeps track of the value for you, and it persists even when the component re-renders.
Example 1: Preserving Component Data Across Re-renders
That still sounds a little abstract, so let’s work through a simple requirement: “Count how many times a component has re-rendered.” First, add an input field to the page. When the user enters a name, the page will display “My name is x” and “I have re-rendered x times.”
// First, define the markup<div> <input value={name} onChange={(e) => setName(e.target.value)} /> <div>My name is {name}</div> <div>I have re-rendered {renderCount} times</div></div>Next, define the data. Here, we use useState to define two variables, name and renderCount, and increment renderCount by 1 every time the component re-renders.
// Handle the dataconst [name, setName] = useState('');const [renderCount, setRenderCount] = useState(0);
useEffect(() => { setRenderCount((prevCount) => prevCount + 1);});Looks simple enough—what could go wrong? In fact, the code above has a major logical flaw. It won’t work, and it will repeatedly throw the following error!
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
This happens because typing triggers a component re-render, which then triggers renderCount + 1, causing another re-render. This creates an infinite loop: update state > trigger render > update state > trigger render… 😭 This is a classic use case for useRef.
Simply define renderCount using useRef instead, and the code will work as expected, because useRef does not cause the component to re-render:
const [name, setName] = useState('');const renderCount = useRef(1);
useEffect(() => { renderCount.current += 1;});本元件重新渲染次數:1
The example above demonstrates how to use the useRef Hook to keep track of values that need to persist across component re-renders.
Example 2: Selecting Elements
React builds a virtual DOM to handle component rendering, so we cannot use querySelector directly: that method only retrieves elements from the real DOM, not React’s virtual DOM. In React, we can use ref to select a virtual DOM element and store the reference with useRef.
const [name, setName] = useState('');const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus();}, []);In this case, you can think of it as a virtual DOM version of querySelector, one that you can use within React components.
Summary
A discussion of useRef wouldn’t be complete without covering useState and other ways to define variables. Each has its own uses and characteristics, so let’s look at how they differ:
Method 1: Define a Variable Outside the Component
let outside = 0;const App = () => { return <div>{outside}</div>;};This is effectively defining a global variable: it is created when the entire application loads and is available throughout the application. This can be convenient in some situations, such as when multiple components need to share the same variable, but it also introduces potential issues:
- Naming conflicts: If multiple components use the same variable name, naming conflicts can occur.
- Difficult to track: When a variable is shared by multiple components, it can be difficult to track how it is modified. This can lead to problems that are hard to debug.
- Difficult to test: This increases the complexity and instability of the code, making its behavior harder to predict and test.
Overall, this isn’t a great approach. If you want to share state between components, you can pass props or use useContext rather than relying on global variables.
Method 2: Define a Variable Inside the Component
const App = () => { let inside = 0; return <div>{inside}</div>;};This is similar to the first method, except that the variable is defined inside the component, avoiding naming conflicts. However, there is one important difference: the variable is reset every time the component re-renders.
Method 3: Use useState
useState is probably the first Hook you encounter when learning React, so I won’t go into detail here. The key point is that calling setState causes the component to re-render.
const App = () => { const [state, setState] = useState(0); return <div>{state}</div>;};Method 4: Use useRef
Similar to useState, but it does not trigger a re-render.
const App = () => { const ref = useRef(0); return <div>{ref.current}</div>;};References
- Learn useRef in 11 Minutes - Web Dev Simplified
- useRef - React Docs
- Why need useRef and not mutable variable? - stack overflow