Introduction:
In React applications, optimizing performance is crucial for delivering a smooth user experience. One common optimization technique involves minimizing unnecessary re-renders, especially in components that frequently update state. While useState is a powerful tool for managing component state, it can sometimes lead to performance issues, particularly when used in scenarios where state changes trigger frequent re-renders. In such cases, useRef can be a valuable alternative for storing values that do not require triggering re-renders. In this blog post, we'll explore how to use useRef to optimize React applications and improve performance.
Understanding useRef:
Before diving into its usage, let's briefly understand what useRef is. useRef is a hook provided by React that allows us to persist values across renders without causing re-renders when the value changes. Unlike useState, changes to useRef values do not trigger component re-renders, making it suitable for scenarios where frequent updates occur without affecting the UI.
Example Scenario:
Let's consider a common scenario where we want to track the scroll position of a webpage and restore it when the user revisits the page. Typically, developers might use useState to store the scroll position, causing re-renders each time the scroll position changes. However, using useRef can help us avoid unnecessary re-renders in this scenario.
Example Implementation:
import React, { useRef, useEffect } from 'react';
function ScrollTracker() {
const scrollPosition = useRef(0);
useEffect(() => {
const handleScroll = () => {
scrollPosition.current = window.scrollY;
// Perform any additional actions based on scroll position
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
// Restore scroll position on component mount
useEffect(() => {
window.scrollTo(0, scrollPosition.current);
}, []);
return (
<div>
{/* Content */}
</div>
);
}
export default ScrollTracker;
Explanation:
In this example, we define a ScrollTracker component that tracks the scroll position of the window using useRef. We initialize a useRef variable named scrollPosition with an initial value of 0. We then utilize the useEffect hook to add a scroll event listener to the window. Whenever the user scrolls, the handleScroll function updates the scrollPosition.current value with the current scroll position.
Notice that updating scrollPosition.current does not trigger re-renders since it is a ref, not state. This ensures that frequent scroll events do not impact the performance of the component.
Additionally, we use another useEffect hook to restore the scroll position when the component mounts. This ensures that the scroll position is maintained even when the user navigates away from and returns to the page.
Conclusion:
In React applications, optimizing performance is essential for delivering a seamless user experience. By leveraging useRef instead of useState for storing values that do not require triggering re-renders, developers can significantly improve the performance of their applications. Whether it's tracking scroll position, managing focus, or caching values, useRef offers a lightweight and efficient solution for optimizing React components. By incorporating useRef into your development workflow, you can ensure that your applications are both fast and responsive, providing users with an enjoyable browsing experience.
Cheat Sheet:
- useState: when you want that on change of this variable the component should update / re-render
- javascript variables: when you want to calculate something on every re-render but don't want to cause re-render
- useRef: when you want to keep some value across re-renders but don't want it to cause re-render
Top comments (3)
great observations! Thank you for the article
hello Aman, to highlight your code blocks like this:
please add the word "javascript" after the three opening backticks in your code blocks
Thanks!!