UseRef
The useRef hook in React provides a way to create and manage a mutable reference that persists across renders. It's commonly used to access or modify a DOM element directly, store a value that doesn't trigger a re-render when changed, or maintain state information between renders without causing an update.
Syntax
const ref = useRef(initialValue);`
initialValue: The initial value of the ref, which can be any type.ref.current: The property where the current value of the ref is stored.
Common Use Cases for useRef
- Accessing DOM elements directly.
- Storing mutable values that don't need to cause re-renders (e.g., timers, previous state values).
Example 1: Accessing a DOM Element
This example demonstrates how useRef is used to access an input element directly.
import React, { useRef } from 'react';
function TextInputFocus() {
// Create a ref for the input element
const inputRef = useRef(null);
const focusInput = () => {
// Focus the input element using the ref
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" placeholder="Click the button to focus" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default TextInputFocus;`
Explanation
- Creating a Ref:
inputRefis created usinguseRefand assigned to the<input>element. - Accessing the Element:
inputRef.currentis used to access the DOM element, allowingfocusInputto call.focus()on it when the button is clicked.
Example 2: Storing a Mutable Value
Here, useRef is used to store the previous value of a state variable without triggering re-renders.
import React, { useState, useEffect, useRef } from 'react';
function PreviousCounter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef(0); // Initialize ref to store previous count
useEffect(() => {
// Update the ref with the current count after every render
prevCountRef.current = count;
}, [count]);
return (
<div>
<h1>Current Count: {count}</h1>
<h2>Previous Count: {prevCountRef.current}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default PreviousCounter;`
Explanation
prevCountRef: Holds the previouscountvalue across renders.- Effect to Update
prevCountRef: After every render, theuseEffectupdatesprevCountRef.currentwith the latestcount, providing access to the previous value without causing re-renders.