2024年6月24日 16:43

How to Use useRef in React: Usage Methods and Scenarios

In React, useRef is a highly valuable Hook primarily used for accessing DOM elements and preserving mutable data across rendering cycles. useRef returns a mutable ref object whose .current property is initialized with the value passed to useRef (initialValue). The returned object remains unchanged throughout the component's lifecycle.

Usage Methods

First, import useRef inside the component:

jsx
import React, { useRef } from 'react';

Then, create a ref object using useRef:

jsx
const myRef = useRef(initialValue);

Here, initialValue serves as the initial value for the .current property of the ref object. Use myRef.current to access or modify this value.

Usage Scenarios

Several common scenarios benefit from using useRef:

1. Accessing DOM Elements

When directly manipulating DOM nodes—such as retrieving input field values or setting focus—use useRef:

jsx
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // Directly access the DOM element to set focus inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Set focus</button> </> ); }

2. Preserving Mutable Values

Use useRef to store values that remain constant across rendering cycles without triggering re-renders:

jsx
function Timer() { const intervalRef = useRef(); useEffect(() => { const id = setInterval(() => { // Perform operations }, 1000); intervalRef.current = id; return () => { clearInterval(intervalRef.current); }; }, []); // ... }

In this example, intervalRef stores the interval timer ID. Although this ID changes across rendering cycles, the change does not trigger re-renders.

3. Tracking Previous Values

useRef can track previous state values without re-renders:

jsx
function Counter() { const [count, setCount] = useState(0); const prevCountRef = useRef(); useEffect(() => { prevCountRef.current = count; }); const prevCount = prevCountRef.current; // Access previous value during rendering // ... }

Here, prevCountRef stores the count value after each render, enabling access to the previous state at any time without triggering re-renders.

标签:React前端