Updating Parent component state from multiple child components not taking updated state value into account

I have a question related to react js.

I have a scenario where we have a state in the parent component. It has to be updated by child component. So that, based on the state value, I’ll do something else in the parent component.

But, If I render multiple child components, the parent’s state is getting updated only once.

Could you please help me understand why the state is updating only once and what would be the possible workaround.

Below is the code sandbox link with the example.

https://codesandbox.io/s/heuristic-cori-8793u?file=/src/App.js

Thanks.

Answer

The problem is caused by the fact that updateCounter has closed over the value of count, so when you call it twice with two child components the ‘old’ value of count is used both times. You can avoid it by using the ‘update’ form of useState. This ensures that you will increment the ‘current’ value of count:

const updateCounter = (num) => {
  setCount(c => c + 1);
  console.log(count);
};

Leave a Reply

Your email address will not be published. Required fields are marked *