How to use React.memo() to not re-render when a new element is added to the component
React.memo() is a higher-order component that can be used to memoize functional components to prevent unnecessary re-renders. When the props of the component being memoized change, React.memo will compare the previous and current props. If there are no changes, the component will not be re-rendered.
To use React.memo to not re-render when a new element is added to the component, you can wrap the component with React.memo and pass a function that specifies the props that should trigger a re-render. In the case of adding a new element, the component should only re-render if the props that contain the list of elements have changed.
Checkout more articles on ReactJS
Here's an example of how to use React.memo to prevent re-rendering when a new element is added to a list:
import React, { useState } from 'react';
const List = React.memo(({ items }) => {
console.log('List rendered');
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}, (prevProps, nextProps) => {
// Only re-render if the items array has changed
return prevProps.items.length === nextProps.items.length;
});
const App = () => {
const [items, setItems] = useState([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
]);
const addItem = () => {
setItems([...items, { id: items.length + 1, text: `Item ${items.length + 1}` }]);
};
return (
<>
<button onClick={addItem}>Add Item</button>
<List items={items} />
</>
);
};
export default App;
In this example, the List
component is memoized using React.memo
. The second argument to React.memo
is a comparison function that compares the previous and current props. In this case, the function compares the items
prop to determine if the component should be re-rendered. The App
component contains a button that adds a new item to the items
state array. When the button is clicked, the List
component is not re-rendered because the comparison function determines that the items
prop has not changed.
Using React.memo
is a simple way to optimize performance by preventing unnecessary re-renders. However, it should be used judiciously, as memoizing too many components can lead to decreased performance due to the overhead of memoization.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! π