Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish what caused rendering of React component: something from the inside or from the outside of the component?

Tags:

reactjs

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?

like image 930
Luka Avatar asked Jul 21 '16 21:07

Luka


People also ask

How do you check what is causing re-render React?

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.

Which method is called when there is an error during rendering in React?

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.

Which method is called just after the rendering of the component?

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.


1 Answers

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}.

like image 152
Ben Hare Avatar answered Nov 24 '22 12:11

Ben Hare