React: Issue with Conditional Rendering and Performance in Large Lists
I tried several approaches but none seem to work. I need help solving After trying multiple solutions online, I still can't figure this out... I'm sure I'm missing something obvious here, but I'm working on a React application that renders a large list of items. The list can have thousands of entries, and I want to implement conditional rendering based on the state. However, I'm facing performance issues when the state changes, causing the entire list to re-render. Initially, I used the `useState` hook to handle the visibility of items, but since the list can be extensive, it results in significant lag. Hereโs a simplified version of my code: ```javascript import React, { useState } from 'react'; const ItemList = ({ items }) => { const [visible, setVisible] = useState([]); const toggleVisibility = (itemId) => { setVisible(prev => { if (prev.includes(itemId)) { return prev.filter(id => id !== itemId); } return [...prev, itemId]; }); }; return ( <ul> {items.map(item => ( <li key={item.id}> <button onClick={() => toggleVisibility(item.id)}>Toggle</button> {visible.includes(item.id) && <span>{item.content}</span>} </li> ))} </ul> ); }; ``` The problem arises when I click to toggle the visibility of an item; the entire list re-renders, and in larger lists, it feels sluggish. I've tried using `React.memo` around the list items to prevent unnecessary re-renders, but it doesnโt seem to help much. Here's how I implemented that: ```javascript const ListItem = React.memo(({ item, onToggle, isVisible }) => { return ( <li> <button onClick={() => onToggle(item.id)}>Toggle</button> {isVisible && <span>{item.content}</span>} </li> ); }); ``` And in my main component: ```javascript {items.map(item => ( <ListItem key={item.id} item={item} onToggle={toggleVisibility} isVisible={visible.includes(item.id)} /> ))} ``` Despite these optimizations, I still experience performance issues. Is there a better approach or best practice for handling conditional rendering in large lists without incurring a performance penalty? Any suggestions would be greatly appreciated! I'm working in a Debian environment. Is this even possible? I recently upgraded to Javascript stable. I'm developing on Ubuntu 22.04 with Javascript. Thanks for taking the time to read this! This is my first time working with Javascript latest. Any suggestions would be helpful.