CodexBloom - Programming Q&A Platform

React 18: How to Handle Multiple State Updates from Child Components Without Causing Unnecessary Renders?

πŸ‘€ Views: 27 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
react performance state-management javascript

I'm performance testing and I'm currently building a dashboard in React 18 where child components need to communicate changes back to the parent component, but I'm running into performance issues due to excessive re-renders. I've set up a parent component that holds state for multiple children, but when a child component updates its state, it appears to cause the entire parent component to re-render, leading to a noticeable lag in performance. Here's a simplified version of my code: ```javascript import React, { useState } from 'react'; const ParentComponent = () => { const [data1, setData1] = useState('Initial Data 1'); const [data2, setData2] = useState('Initial Data 2'); const handleDataChange1 = (newData) => { setData1(newData); }; const handleDataChange2 = (newData) => { setData2(newData); }; return ( <div> <ChildComponent1 data={data1} onDataChange={handleDataChange1} /> <ChildComponent2 data={data2} onDataChange={handleDataChange2} /> </div> ); }; const ChildComponent1 = ({ data, onDataChange }) => { return <input value={data} onChange={(e) => onDataChange(e.target.value)} />; }; const ChildComponent2 = ({ data, onDataChange }) => { return <input value={data} onChange={(e) => onDataChange(e.target.value)} />; }; ``` While this approach works, I noticed that changing the input in `ChildComponent1` causes `ParentComponent` to re-render along with `ChildComponent2`, even if `data2` is not being changed. I tried using `React.memo` on my child components to prevent unnecessary re-renders, but it didn't seem to help much. Here’s how I implemented it: ```javascript const ChildComponent1 = React.memo(({ data, onDataChange }) => { return <input value={data} onChange={(e) => onDataChange(e.target.value)} />; }); const ChildComponent2 = React.memo(({ data, onDataChange }) => { return <input value={data} onChange={(e) => onDataChange(e.target.value)} />; }); ``` Despite using `React.memo`, the parent still re-renders when I update one of the inputs. I also considered using `useReducer` for more complex state management, but I'm not sure if that would solve the re-render issue. Is there a better way to manage state in this scenario without causing unnecessary re-renders? Any suggestions or best practices would be greatly appreciated! Any advice would be much appreciated. Any advice would be much appreciated.