useRef is a powerful React Hook that allows you to create and manage mutable references that persist between renders. Unlike state, changing the value of a useRef object does not trigger a re-render, making it ideal for scenarios like accessing DOM elements or managing values that don’t directly affect the UI.
What is useRef?
useRefis a React Hook that lets you reference a value that’s not needed for rendering.
— React Docs
This makes useRef an essential tool for managing mutable values or interacting with DOM elements without re-rendering the component.
Syntax:
const ref = useRef(initialValue);
Parameters
initialValue: The value assigned to thecurrentproperty of the ref object during the first render. This value is ignored in subsequent renders.
Returns
current: A mutable property of theuseRefobject. It holds the reference’s current value, which can be updated without affecting the component’s render cycle.
Usage
Accessing DOM Elements:
UseuseRefto directly interact with HTML elements (e.g., focusing an input field).Example:
import React, { useRef } from "react"; function FocusInput() { // Create a ref to hold the input element const inputRef = useRef(null); const handleFocus = () => { // Focus the input element on button click inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={handleFocus}>Focus Input</button> </div> ); } export default FocusInput;What’s Happening?
- The
inputRefis assigned to the<input>element using therefattribute. - When the button is clicked, the
handleFocusfunction usesinputRef.currentto call thefocus()method on the input.
- The
Storing Mutable Values:
UseuseRefto store values that need to persist across renders but don’t require UI updates. This is particularly useful for tasks like tracking intervals or keeping the previous value of a prop.Example:
import React, { useRef } from "react"; const Counter = () => { // Create a ref to store the counter value const countRef = useRef(0); const handleClick = () => { // Update the value without re-rendering countRef.current += 1; console.log(`You clicked ${countRef.current} times!`); }; // Logs on every re-render console.log("Rendering happened"); return ( <div> <button onClick={handleClick}>Click me!</button> {/* This won't update on its own */} <p>Counter value: {countRef.current}</p> </div> ); }; export default Counter;Key Points:
- The
countRef.currentvalue updates internally without causing a re-render. - The value persists between renders, but changes to it won’t reflect in the DOM automatically unless the component is re-rendered.
- The
Why use useRef?
Key benefits:
- Persistence: The
currentvalue remains consistent across renders. - Efficiency: Updating
useRefvalues does not trigger a re-render, making it ideal for performance-critical tasks. - Direct DOM Access: Perfect for manipulating DOM elements without additional lifecycle hooks.
Use cases:
- Managing focus, text selection, or media playback.
- Storing mutable variables like timers, intervals, or previous values.
- Preventing re-renders caused by frequent updates to non-critical data.
Summary
useRef is an essential tool in React for managing mutable data and interacting with DOM elements without triggering re-renders. Whether you’re building an interactive form, managing focus, or optimizing performance, useRef provides a simple and effective solution.
Example repository
Check out the full working examples in the GitHub Repository.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me, I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.