Medium
In this e-commerce product list component, what's causing unnecessary re-renders and how would you fix it?
1const ProductList = ({ products, onAddToCart }) => {2 const [sortedProducts, setSortedProducts] = useState([]);34 const sortProducts = () => {5 return products.sort((a, b) => b.price - a.price);6 };78 useEffect(() => {9 setSortedProducts(sortProducts());10 }, [products]);1112 const handleAddToCart = (productId) => {13 onAddToCart(productId);14 };1516 return (17 <div className="grid grid-cols-3 gap-4">18 {sortedProducts.map(product => (19 <div key={product.id} className="p-4 border rounded">20 <h3>{product.name}</h3>21 <p>${product.price}</p>22 <button onClick={() => handleAddToCart(product.id)}>23 Add to Cart24 </button>25 </div>26 ))}27 </div>28 );29};