Member-only story
Optimizing Performance in React: Building a Shopping Cart with `React.memo` and `useCallback`
When building React applications, especially those with complex UIs like a shopping cart, performance optimization becomes essential. Unnecessary re-renders can lead to sluggish user experiences. In this article, we’ll explore how to optimize a React shopping cart using React.memo
and useCallBack
to prevent unnecessary renders and ensure a smooth user experience.
Scenario: A Shopping Cart with Multiple Components
Imaging a scenario where your React application has a shopping cart feature. The cart consists of multiple components, such as product list, cart summary, and checkout button. Each of these components should update only when necessary to avoid performance bottlenecks.
Step 1: Using `React.memo` to Prevent Unnecessary Re-renders
React.memo
is a higher-order component that prevents re-renders of a component if its props have not changed. Let’s apply it our product list component.
import React, { memo } from 'react';
const ProductList = memo(({ products, addToCart }) => {
return (
<div>
{products.map(product => (
<div key={product.id}>
<h2>{product.name}</h2>
<button onClick={() => addToCart(product)}>Add to Cart</button>
</div>
))}
</div>
);
});