The useRef hook is a built-in React hook used to persist values across renders without causing re-renders. It's often used to interact with DOM elements directly and to store values that need to persist between renders but do not necessarily need to trigger a re-render.
The useRef hook is primarily used for two purposes:
const myRef = useRef(initialValue);
The reference object returned by useRef has a current property, which is where the actual value is stored.
const MyComponent = () => { const inputRef = useRef(null); const focusInput = () => { // Access the DOM node and focus it inputRef.current.focus(); }; return ( <div> <input ref={inputRef} /> <button onClick={focusInput}>Focus Input</button> </div> ); };
const TimerComponent = () => { const countRef = useRef(0); const increment = () => { countRef.current++; console.log(countRef.current); // This will log the updated value }; return ( <div> <p>Current count (does not trigger re-render): {countRef.current}</p> <button onClick={increment}>Increment</button> </div> ); };
const ScrollToTop = () => { const topRef = useRef(null); const scrollToTop = () => { topRef.current.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div ref={topRef}> <ol> <li> <strong>Storing Previous State</strong>: If you need to track the previous value of a prop or state value. </li> </ol> <pre class="brush:php;toolbar:false"> const PreviousState = ({ count }) => { const prevCountRef = useRef(); useEffect(() => { prevCountRef.current = count; // Store the current value in the ref }, [count]); return ( <div> <p>Current Count: {count}</p> <p>Previous Count: {prevCountRef.current}</p> </div> ); };
Avoiding Re-renders for Complex Values: If you have a large object or complex data structure that doesn't need to trigger a re-render, useRef can store it without affecting the component’s performance.
Tracking Interval or Timeout: You can store IDs of timeouts or intervals to clear them later.
const myRef = useRef(initialValue);
Feature | useRef | useState | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
No (does not trigger a re-render) | Yes (triggers a re-render when state changes) | |||||||||||||||
Use Case | Storing mutable values or DOM references | Storing state that affects rendering | |||||||||||||||
Value storage | Stored in current property | Stored in state variable | |||||||||||||||
Persistence across renders | Yes (keeps value across renders without triggering re-render) | Yes (but triggers re-render when updated) |
Here’s an example where useRef is used for form validation, focusing on an input field when it’s invalid.
import React, { useRef, useState } from 'react'; const FormComponent = () => { const inputRef = useRef(); const [inputValue, setInputValue] = useState(''); const [error, setError] = useState(''); const validateInput = () => { if (inputValue === '') { setError('Input cannot be empty'); inputRef.current.focus(); // Focus the input element } else { setError(''); } }; return ( <div> <input ref={inputRef} type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> {error && <p>
The useRef hook is incredibly useful for dealing with mutable values and direct DOM manipulation in React. Whether you're working with form elements, tracking the previous state, or interacting with third-party libraries, useRef provides a clean, efficient solution. By using useRef, you can maintain persistence without triggering unnecessary re-renders, which makes it a great choice for performance-sensitive operations.
The above is the detailed content of Mastering Reacts useRef Hook: Working with DOM and Mutable Values. For more information, please follow other related articles on the PHP Chinese website!