ReactJS - Handling dynamic component styles based on user interactions causing performance issues
I've hit a wall trying to I've been working on this all day and Does anyone know how to After trying multiple solutions online, I still can't figure this out. After trying multiple solutions online, I still can't figure this out. I'm facing a performance issue in my React application where I'm dynamically changing styles based on user interactions, and it's causing noticeable lag, especially on slower devices. I'm using React 17.0.2 and styled-components for my styling. The problem arises when I change the state that determines the styles of multiple components simultaneously. For instance, I have a list of items where clicking on each item toggles a 'selected' state that alters its background color and border properties. Here's a simplified version of my component: ```javascript import React, { useState } from 'react'; import styled from 'styled-components'; const ListItem = styled.div` padding: 10px; margin: 5px; cursor: pointer; background-color: ${(props) => (props.selected ? 'lightblue' : 'white')}; border: ${(props) => (props.selected ? '2px solid blue' : '2px solid transparent')}; `; const ItemList = () => { const [selectedItems, setSelectedItems] = useState([]); const toggleSelect = (itemId) => { setSelectedItems((prev) => { if (prev.includes(itemId)) { return prev.filter((id) => id !== itemId); } return [...prev, itemId]; }); }; return ( <div> {[1, 2, 3, 4, 5].map((itemId) => ( <ListItem key={itemId} selected={selectedItems.includes(itemId)} onClick={() => toggleSelect(itemId)} > Item {itemId} </ListItem> ))} </div> ); }; export default ItemList; ``` The lag is especially apparent when I click multiple items quickly. I also tried using `React.memo()` on `ListItem`, but it doesn't seem to help much since each item is still rerendered for style updates. I checked the React DevTools and noticed a significant number of renders happening, which I suspect is causing the performance drop. Is there a more efficient way to handle dynamic styles without causing these performance hits? Any advice on best practices for this kind of situation would be greatly appreciated! My development environment is macOS. This is my first time working with Javascript 3.9. This is for a microservice running on Ubuntu 22.04. I'm open to any suggestions. I'm open to any suggestions. This is for a CLI tool running on Linux. Has anyone dealt with something similar?