Selective re-rendering in React is a vital concept for anyone diving into the world of React development. Understanding it can solve common issues like slow app performance and unresponsive user interfaces. If you’re keen to boost your coding skills and build efficient applications, keep reading to explore this transformative topic.
What is Selective Re-rendering in React?
Selective re-rendering in React is a performance optimization technique where only the components that actually need updates are re-rendered, instead of re-rendering the entire component tree.
How React Normally Re-renders Components
By default, when a component’s state or props change, React re-renders that component and all of its child components. This ensures the UI stays in sync with data, but it can also lead to unnecessary re-renders.
The Problem of Unnecessary Re-renders
Unnecessary re-renders happen when components update even though their data hasn’t changed. This can:
- Slow down the application
- Increase CPU usage
- Cause laggy UI in large apps
Why Do Unnecessary Re-renders Happen?
- State Updates
Whenever state changes, React triggers a re-render—even if the new state is similar to the previous one. - Parent Component Re-renders
When a parent component re-renders, all its children re-render by default, even if their props remain unchanged. - Props Changes
If props change (even slightly), React re-renders the child component. This includes shallow changes like new object or array references. - Inline Functions and Objects
Creating functions or objects inside JSX causes new references on every render, leading React to think something changed.
Example:
<button onClick={() => handleClick()}>Click</button>
This creates a new function every render.
Benefits of Selective Re-rendering
- Improved Performance
Reduces unnecessary updates, making the app faster. - Faster UI Updates
Only the required components update, leading to smoother interactions. - Better Scalability
Helps maintain performance as the app grows in size and complexity. - Optimized Resource Usage
Lowers CPU and memory usage by avoiding redundant work.
Key Techniques for Selective Re-rendering in React
1. React.memo
How It Works
React.memo is a higher-order component that prevents re-rendering if props haven’t changed.
Example:
const MyComponent = React.memo(({ value }) => {
return <div>{value}</div>;
});
When to Use
- Functional components
- Components that receive stable props
- UI elements that render frequently
2. useMemo Hook
Memoizing Values
useMemo caches computed values so they don’t get recalculated on every render.
Example:
const expensiveValue = useMemo(() => computeValue(data), [data]);
Preventing Recalculations
Useful when calculations are heavy or depend on specific inputs.
3. useCallback Hook
Preventing Function Recreation
useCallback memoizes functions to avoid creating new instances on each render.
Example:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Use Cases
- Passing functions to child components
- Avoiding unnecessary child re-renders
4. shouldComponentUpdate (Class Components)
Controlling Updates Manually
Allows class components to decide whether they should re-render.
Example:
shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
}
5. Key Prop Optimization
Role of Keys in Rendering
Keys help React identify which elements have changed, been added, or removed.
Best Practice:
items.map(item => <Item key={item.id} />)
- Use stable, unique keys
- Avoid using array index as key when possible
Selective re-rendering in React
javascript
import React, { useState } from 'react';
function Counter({ value }) {
const [count, setCount] = useState(value);
const handleClick = () => {
setCount(count + 1);
};
return (
Count: {count}
);
}
function App() {
const [showCounter, setShowCounter] = useState(true);
const toggleCounter = () => {
setShowCounter(!showCounter);
};
return (
{showCounter && }
);
}
export default App;
Explanation of the Code
Here’s a neat little code snippet using React, a popular JavaScript library for building user interfaces. Let’s break it down:
- First, we import React and the useState hook. The useState hook lets us add state to our functional component.
- The Counter component’s purpose is to display a count value, which is initially set using a prop called value. When you click the “Increment” button, this count increases.
- Within the Counter component, the setCount function is used to update the count by adding one whenever the button is clicked.
- The App component controls the display of the Counter component through the showCounter state.
- We have a toggleCounter function inside App, changing the visibility of the Counter component using a button titled “Toggle Counter”.
- Finally, the App component is exported, enabling it to be used elsewhere in an application.
Output
Count: 0
Practical Examples– Before vs After Optimization
Before Optimization (Unnecessary Re-renders)
In this example, the child component re-renders every time the parent updates—even when props haven’t changed.
import React, { useState } from "react";
const Child = ({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click Me</button>;
};
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child onClick={() => console.log("Clicked")} />
</div>
);
}
Problem:
- A new function is created on every render
- Child re-renders unnecessarily
After Optimization (Selective Re-rendering Applied)
import React, { useState, useCallback } from "react";
const Child = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click Me</button>;
});
export default function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child onClick={handleClick} />
</div>
);
}
Code Snippets Showing Performance Gains
Expensive Calculation Without Optimization
const result = expensiveCalculation(data);
With useMemo Optimization
const result = useMemo(() => expensiveCalculation(data), [data]);
Impact:
- Avoids repeated heavy computations
- Improves rendering speed significantly in large datasets
Common Mistakes to Avoid
- Overusing Memoization
- Using
React.memo,useMemo, oruseCallbackeverywhere can backfire - Adds complexity and sometimes reduces performance
2. Premature Optimization
- Optimizing before identifying actual performance issues
- Focus first on building a working app, then optimize bottlenecks
3. Ignoring Component Structure
- Poorly structured components can cause excessive re-renders
- Deep nesting and unnecessary state sharing increase render cycles
Best Practices
1. Keep Components Small
- Smaller components are easier to manage and optimize
- Limits the impact of re-renders
2. Use Memoization Wisely
- Apply only where re-renders are frequent and costly
- Avoid unnecessary usage in simple components
4. Measure Performance Before Optimizing
- Always analyze performance before applying optimizations
- Focus on real bottlenecks instead of assumptions
Tools to Measure Rendering Performance
React DevTools Profiler
- Tracks which components re-render and why
- Helps identify performance bottlenecks
- Provides render timing insights
Chrome Performance Tab
- Records runtime performance of your app
- Shows CPU usage, rendering time, and frame drops
- Useful for deep performance analysis
Real-Life Applications of Selective Re-rendering in React
-
Facebook News Feed: Facebook, a massive user of React, leverages selective re-rendering in its News Feed. By using React’s built-in performance optimisations, only parts of the feed that have changed are re-rendered. This speeds up the loading process.
Through usingclass Post extends React.PureComponent { render() { return{this.props.content}; } }React.PureComponent, Facebook ensures that components update only if their props or state changes, making every feed interaction smoother.
-
Twitter Timeline Updates: Twitter has designed its timeline in such a way that only new tweets trigger re-rendering, which reduces the processing power required.
UtilizingshouldComponentUpdate(nextProps) { return this.props.tweet.id !== nextProps.tweet.id; }shouldComponentUpdate, Twitter minimises unnecessary updates, ensuring better scrolling performance and reducing lag.
-
Instagram Photo Feed: Like its parent company Facebook, Instagram benefits from React’s selective re-rendering for its photo feed, leading to better user experience.
By employingconst PhotoFeed = React.memo(({photos}) => { return{photos.map(photo =>; });)} React.memo, the app optimises the component rendering, boosting speed and reducing unnecessary re-renders for unchanged photo feeds.
Nailing React Re-renders- Selective re-rendering in React
- How does selective re-rendering improve the performance of a React application?
Selective re-rendering optimises performance by updating only the components that need to change, rather than re-rendering the entire DOM. This is crucial in large-scale applications where unnecessary re-renders can slow things down - What is a common method to implement selective re-rendering?
The `shouldComponentUpdate` lifecycle method is often used in class components to implement selective re-rendering. By returning `false`, you can prevent a component from updating.shouldComponentUpdate(nextProps, nextState) {
return nextProps.someValue !== this.props.someValue;
} - Can you implement selective re-rendering in functional components?
Yes, with React’s `React.memo()` higher-order component, we can achieve selective re-rendering in functional components.const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
}, areEqual); - What are the differences between React’s PureComponent and React.memo()?
`PureComponent` automatically implements a shallow comparison on class components, whereas `React.memo()` provides similar functionality for functional components. - Why might selective re-rendering not always work as expected?
Mistakes in state management or improper prop comparisons can lead to unexpected re-renders, nullifying performance gains.
Discover our AI-powered js online compiler, where you can instantly write, run, and test your code. Our intelligent compiler simplifies your coding experience, offering real-time suggestions and debugging tips, streamlining your journey from coding novice to expert with ease. Explore it today and boost your coding skills!
Conclusion
Selective re-rendering in React improves your app’s performance, making it more responsive and efficient. By mastering this skill, you’ll feel a sense of achievement and sharpen your coding expertise. Eager to explore more? Dive into various programming languages on Newtum. Give it a try!
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.