React - How to detect when all sub-components of a parent component are visible to the user?
There are two lifecycle hooks in React that are called after a component's DOM has rendered:
- componentDidMount
- componentDidUpdate (you're interested in this one)
For your use case your parent component P is interested when N child components have each satisfied some condition X. X can be defined as a sequence:
- async operation completed
- component has rendered
By combining the state of the component and using the componentDidUpdate
hook, you can know when the sequence has completed and your component meets condition X.
You can keep track of when your async operation has completed by setting a state variable. For example:
this.setState({isFetched: true})
After setting state, React will call your components componentDidUpdate
function. By comparing the current and previous state objects within this function you can signal to the parent component that your async operation has completed and your new component's state has rendered:
componentDidUpdate(_prevProps, prevState) {
if (this.state.isFetched === true && this.state.isFetched !== prevState.isFetched) {
this.props.componentHasMeaningfullyUpdated()
}
}
In your P component, you can use a counter to keep track of how many children have meaningfully updated:
function onComponentHasMeaningfullyUpdated() {
this.setState({counter: this.state.counter + 1})
}
Finally, by knowing the length of N you can know when all meaningful updates have occurred and act accordingly in your render method of P:
const childRenderingFinished = this.state.counter >= N