Home > Software engineering >  React parent method passed in child component has stale state
React parent method passed in child component has stale state

Time:12-22

In my App.js, I have the following:

const(sound,SetSound) = useState('beep');
return (
<Childcomponent
    sound={sound}
    setSound={setSound}
    playSound={playSound}
/>
...

In my ChildComponent I do the following:

props.setSound('honk');
props.playSound();

Instead of honking it beeps. What am I missing?

In app.js I catch keypress 'a' to call playSound(). When I do that it honks after the childComponent updated it. Somehow the props.playSound() is stale though. If I display {sound} in childComponent, it shows the updated 'honk'.

I tried 'binding' with
playSound={() => playSound()} But it still beeps instead of honking.

How do I honk from ChildComponent?

CodePudding user response:

What does your playSound() function look like? Seems like playSound() is still using the old state of sound.

In App.js, I would pass the value to the playSound function so that it uses the correct, updated value of sound:

function playSound(sound) {
  // Plays the sound with the argument passed in.
}

CodePudding user response:

Once you call setSound with value 'honk', it won't be available to playSound in the same tick. You've to wait for next render cycle and then call props.playSound()

Or you could do something like this

// This will ensure that playSound is called after setting the state
props.setSound('honk', () => props.playSound());
  • Related