I have two nested react components: Outer
and Inner
. Whenever I call setState
of Inner
, render
of inner component gets invoked. Also, whenever I call setState
of outer component, render
functions of both outer and inner components gets invoked.
I would like to distinguish those two cases and detect what coused rendering of the inner component. My render
function of Inner
should behave differently depending on that. How can I do that?
Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
The componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.
You can make use of the fact that the componentWillReceiveProps is only called when the component is receiving new props (check out here: http://busypeoples.github.io/post/react-component-lifecycle/), not when setState is called, and importantly they don't even have to be different props than the existing ones (per https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops). So you should be able to do something along the lines of
componentWillReceiveProps() {
this.setState({parentUpdated: true});
}
render() {
if (this.state.parentUpdated) {
// Render one way
} else {
// Render the other way
}
}
Although you would also need to unset that after the render somehow, or just ensure that every call to this.setState also includes {parentUpdated: false}.
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