Introduction
As your React application grows in size, you may start to notice a decrease in performance. One of the most common causes of slow performance is the unnecessary re-rendering of components. Memoization is a technique that can help optimize performance by reducing the number of unnecessary re-renders. In this article, we will explore how to use memoization in React.
Let's say we have a list of items that we want to render in our app. Each item contains some data that we fetch from an API. We want to optimize the rendering of the items so that we don't make unnecessary API calls when the items haven't changed.
Step 1: Create a new React component
Let's create a new React component called ItemList
that will render a list of items. In the src
directory of your React project, create a new file called ItemList.js
and add the following code:
import React, { useState, useEffect } from 'react';
function ItemList({ items }) {
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, [items]);
async function fetchData() {
const newData = await fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json());
setData(newData);
}
return (
<div>
{data.map(item => (
<div key={item.id}>
<h2>{item.title}</h2>
<p>{item.body}</p>
</div>
))}
</div>
);
}
export default ItemList;
This component uses the useState
hook to manage its state and the useEffect
hook to fetch data from an API when the items
prop changes.
Step 2: Memoize the component
Now, let's use memoization to optimize the performance of the ItemList
component. We can do this by wrapping the component with the React.memo
function and passing a custom comparison function as the second argument. In ItemList.js
, replace the export statement with the following code:
export default React.memo(ItemList, (prevProps, nextProps) => {
return JSON.stringify(prevProps.items) === JSON.stringify(nextProps.items);
});
This will memoize the component and only re-render it if the items
prop has changed.
Step 3: Test the app
To test our app, we can add the ItemList
component to our app. Open the App.js
file in the src
directory and replace the default code with the following:
import React, { useState } from 'react';
import ItemList from './ItemList';
function App() {
const [items, setItems] = useState(['item1', 'item2']);
function addItem() {
setItems([...items, `item${items.length + 1}`]);
}
return (
<div>
<h1>Items:</h1>
<ItemList items={items} />
<button onClick={addItem}>Add Item</button>
</div>
);
}
export default App;
Now, run the app using the following command in the terminal:
npm start
You should see the ItemList
component rendered in the browser with the data fetched from the API. Clicking the "Add Item" button should add a new item to the list without causing unnecessary API calls.
That's it! We have successfully optimized the performance of our ItemList
component using memoization.
To replicate this example on your local machine, you will need to have Node.js and npm installed. You can then create a new React project using Create React App and follow the steps outlined in this article to create the ItemList
component and memoize it using React.memo
.