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
You CAN'T avoid that since a Component always has to re-render if its internal state changes. So you have two possible approaches to solve performance issues in this scenario:
React.memo(), this way every time one of your children updates a state in the Parent component, all the children that don't care and don't receive that updated state as a prop, won't re-render.Redux, this way only the components that use a particular slice of the state will re-render when that state changes.In any case, if in your Components that are on top of the Tree, ( Parents ) you perform heavy calculations, always wrap them in useMemo() hooks, same goes with functions and useCallback(), this way you will be able to address most of your performance issues.
Regarding the question about race-condition, react useState can be used with a callback like this, to be sure that when it executes it will have access to the most up-to-date value of that state in that moment:
const [state, setState] = useState(0)
setState(currentState => currentState + 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With