In our react application, We have parent-child component. Child component calls parent method to update parent state values. Here is sample code
//Parent component
const parent = ({ items }) => {
const [information, setInformation] = useState([]);
const updateParentInformation = (childUpdate) => {
setInformation(information + childUpdates)
}
return (
<div>
<div>{information}</div>
...
{items.map((item) => {
return (
<ChildComponent item={item} updateParentInformation={updateParentInformation} />
)})}
</div>
)
}
//Child Component
const ChildComponent = ({ item, updateParentInformation }) => {
useEffect(() => {
const cardInformation = calculateCardInformation(item)
updateParentInformation(cardAmpScripts)
}, [item])
return (
<div>
.....
</div>
)
}
So child component calls the parent's updateParentInformation function to update the parent state, which re-renders parent components. I have a few questions here
In some cases, we may have 100-150 Child components, in such cases our parents will re-render a lot, How to avoid this. We can avoid this throgh this code
.... let recievedUpdates = 0 const updateParentInformation = (childUpdate) => { recievedUpdates++ if(recievedUpdates == items.length { setInformation(information + childUpdates) } }
If this is a possible solition then I have question 2
- How to avoid race-condition when child component calls parent's updateParentInformation. For example child 1 is called updateParentInformation function and at the same time child 2 is also called updateParentInformation, in this case we may lose updates from one child.