React.memo
In React, React.memo is a Higher-Order Component (HOC) that helps improve performance by preventing unnecessary re-renders of functional components. It use Memoization technique to optimize the performance of React components by caching the result of the component’s rendering and reusing it if the component’s props remain unchanged. It leads to lower memory usage due to less re-render. Here’s a breakdown of how it works:
Syntax:
const MemoizedComponent = React.memo(FunctionalComponent);
Example: Below is the code example:
// index.js
import React from 'react'
const ListItem = React.memo(({ value }) => {
console.log(`Rendering item with value: ${value}`);
return (
<div>
<p>Value: {value}</p>
</div>
);
});
const List = ({ itemCount = 10 }) => {
const items =
Array.from({ length: itemCount }, (_, index) => ({
id: index,
value: Math.random() * 1000
// Generate a random number
}));
return (
<div>
<h2>List</h2>
{items.map(item => (
<ListItem key={item.id} value={item.value} />
))}
</div>
);
};
const root = ReactDOM.createRoot(
document.getElementById('root')
);
root.render(
<div id='main_container'>
<div>
<img src=
'https://media.w3wiki.org/gfg-gg-logo.svg' alt='gfg_logo' />
</div>
<List />
</div>
);
Output:
Mastering Performance Optimization Techniques with React Hooks
In this article, we will explore advanced performance optimization techniques using React Hooks. We’ll delve into memoization, callback optimization, preventing unnecessary renders, state updates, and more. By mastering these techniques, developers can significantly enhance the performance of their React applications.