I’m building a React application where I have a parent component that holds the state and several child components that need to receive and update this state. I’m using props to pass the state and a callback function to update the state from the child components. However, I’m encountering issues where the state updates aren’t reflecting immediately in the child components, or the state becomes inconsistent.
function ParentComponent() {
const [data, setData] = useState([]);
const updateData = (newData) => {
setData(newData);
};
return (
<div>
<ChildComponent data={data} updateData={updateData} />
<AnotherChildComponent data={data} />
</div>
);
}
function ChildComponent({ data, updateData }) {
const handleClick = () => {
const updatedData = [...data, 'New Item'];
updateData(updatedData);
};
return (
<div>
<button onClick={handleClick}>Add Item</button>
</div>
);
}
function AnotherChildComponent({ data }) {
return (
<ul>
{data.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
What is the best practice for managing state between parent and child components in React?
How can I ensure that all child components receive the updated state immediately?
Are there any performance concerns with this approach, and how can I optimize it?