I have a case where I need to update the parent before showing a modal in a child (portaled to the end anyways).
I wish to have a sequence where:
- The parent updates a state
- The parent re-renders to update some DOM elements (with unchanged child)
- Child updates a state or receives prop
- Child re-renders to show the modal
I know in a more general case, I can use react-transition-groups to show the modal with a delay. But I'm using a third-party modal and its events are not exposed to me. I would like to avoid writing my own modal since it's used extensively and it'd be a pain to refactor all of them.
Related: Does React keep the order for state updates?
no matter how many setState() calls in how many components you do inside a React event handler, they will produce only a single re-render at the end of the event.
The dumb part of the question asked at 3am
This is what I have right now:
Component:
Components:
<Parent>
{!this.state.hideOtherThing && <div />
<Child showThing={this.state.hideOtherThing} />
</Parent>
Pseudo Code:
class Parent extends React.Component {
...
hideOtherThing = () => {
// make changes to hide other things...
...
this.setState({ hideOtherThing: true },
// callback, should be executed first?
() => console.log("setState", this.state.hideOtherThing));
}
...
}
class Child extends React.Component {
...
componentDidUpdate(prevProps) {
if (prevProps.showThing === false && this.props.showThing === true) {
console.log("child update", this.props.showThing);
}
}
...
render() {
console.log("child render", this.props.showThing);
return...
}
}
On update, I was hoping for something like
"child render" false // previous state
"setState" true
"child update" true
"child render" true
However, I got the exact opposite:
"child render" false // previous state
"child render" true
"child update" true
"setState" true
I tried to use the prop directly; I tried to set a child state from props; I tried setTimeout
, but it seems the child is fixated on updating first. How do I render child changes after parent changes?