CodexBloom - Programming Q&A Platform

React 18: Problems with Conditional Rendering and useMemo causing unnecessary re-renders

šŸ‘€ Views: 15 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-28
reactjs performance useMemo javascript

I'm building a feature where I'm working on a personal project and I'm working with an scenario in my React 18 application where I conditionally render a component based on a state variable, but it seems to be re-rendering unnecessarily despite using `useMemo`. The component in question is a child rendering a list of items based on a search term. I implemented `useMemo` to optimize the list rendering, but I noticed that every time I type in the search input, the entire list is re-rendered, leading to performance optimization. Here's a simplified version of my code: ```javascript import React, { useState, useMemo } from 'react'; const ItemList = ({ items }) => { const [searchTerm, setSearchTerm] = useState(''); const filteredItems = useMemo(() => { console.log('Filtering items...'); return items.filter(item => item.toLowerCase().includes(searchTerm.toLowerCase())); }, [items, searchTerm]); return ( <div> <input type="text" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Search items..." /> <ul> {filteredItems.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> </div> ); }; const App = () => { const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape']; return <ItemList items={items} />; }; export default App; ``` I've confirmed that the `filteredItems` variable is only recalculated when `items` or `searchTerm` changes, but the parent component, `App`, is re-rendering every time I change the input field. I tried wrapping `ItemList` in `React.memo`, but it didn't change anything. This is the behavior I’m observing in the React DevTools: the `App` component re-renders on every keystroke, triggering the child component to re-render as well. I'm wondering if there's a way to prevent this or if I need to rethink my component structure. Any insights would be appreciated! I'm working with Javascript in a Docker container on Ubuntu 20.04. Has anyone else encountered this? What am I doing wrong?