Mastering React Hooks: A Beginner's Guide to useRef
SRINIVAS K
Serving NP | Software Engineer specializing in React, TypeScript, JavaScript and Next.js | Building Scalable Web Applications with a Focus on Performance
?? Mastering React Hooks: A Beginner's Guide to useRef
React hooks offer a powerful way to manage state and side effects in functional components. One essential but often underused hook is useRef. Let’s dive into its core functionality and explore practical examples to master this hook. ??
?? What is useRef?
The useRef hook allows you to persist values across renders without causing a re-render. It can hold a reference to a DOM element or store mutable values in a component. This is especially useful for accessing DOM elements or keeping values that don't trigger re-renders when changed (unlike useState).
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null); // Initialize ref to store input reference
const handleFocus = () => {
inputRef.current.focus(); // Access the input element and focus it
};
return (
<div>
<input ref={inputRef} type="text" placeholder="Enter something" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
?? Breakdown:
Unlike useState, updating a useRef value doesn’t trigger a re-render. This is key when you need to store data that changes frequently (e.g., timers, mutable objects) without affecting component performance.
? Important Concepts to Master:
const renderCount = useRef(0); // Initialize a mutable value
renderCount.current += 1; // Update the value without re-rendering
// useRef values are not reactive, meaning updates to current won’t cause your component to re-render.
const [count, setCount] = useState(0); // ? Wrong: Triggers re-render on every update
const countRef = useRef(0); // ? Correct: Updates without causing re-render
Accessing DOM Elements Directly One of the main use cases for useRef is accessing DOM elements directly. This is often needed for focus, animations, or third-party libraries:
const inputRef = useRef(null); // Store reference to the input element
inputRef.current.focus(); // ? Correct: Access DOM element without re-rendering
const [name, setName] = useState('John');
const prevNameRef = useRef(name);
useEffect(() => {
prevNameRef.current = name; // Store the previous name value
}, [name]);
console.log(prevNameRef.current); // Access the previous name
// This is helpful when you need to compare the current state with the previous one without triggering re-renders.
?? Practical Example: Tracking Timer Without Re-rendering
Let's take an example where we use useRef to track a timer without causing re-renders:
function Timer() {
const [seconds, setSeconds] = useState(0);
const timerRef = useRef(null); // Store timer ID
const startTimer = () => {
timerRef.current = setInterval(() => {
setSeconds((prev) => prev + 1); // Correct: Use function to access the latest state
}, 1000);
};
const stopTimer = () => {
clearInterval(timerRef.current); // Stop the timer
};
return (
<div>
<p>Seconds: {seconds}</p>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
}
Here, timerRef holds the timer ID, allowing you to control the interval without causing unnecessary re-renders when starting or stopping the timer.
?? Conclusion:
useRef is a powerful hook in React, offering flexibility to manage DOM elements and mutable values without triggering re-renders. It’s perfect for optimizing performance, managing focus, or accessing previous values across renders.
?? Tip: Remember, use useRef when you need persistent values that don’t trigger UI updates. Happy coding!
Serving NP | Software Engineer specializing in React, TypeScript, JavaScript and Next.js | Building Scalable Web Applications with a Focus on Performance
1 周checkout the new article to handle complex state logic in React and streamline your code for better performance! --> https://www.dhirubhai.net/posts/srinivasthedeveloper_reactjs-usereducer-frontenddevelopment-activity-7253283207242997760-xKlV
Frontend Developer @Zolvit (Vakilsearch)
1 个月Very informative ????