Trace why a React component is re-rendering

后端 未结 6 1905
傲寒
傲寒 2020-12-04 04:57

Is there a systematic approach to debug what is causing a component to re-render in React? I put a simple console.log() to see how many time it renders, but am having troubl

6条回答
  •  旧时难觅i
    2020-12-04 05:05

    Here are some instances that a React component will re-render.

    • Parent component rerender
    • Calling this.setState() within the component. This will trigger the following component lifecycle methods shouldComponentUpdate > componentWillUpdate > render > componentDidUpdate
    • Changes in component's props. This will trigger componentWillReceiveProps > shouldComponentUpdate > componentWillUpdate > render > componentDidUpdate (connect method of react-redux trigger this when there are applicable changes in the Redux store)
    • calling this.forceUpdate which is similar to this.setState

    You can minimize your component's rerender by implementing a check inside your shouldComponentUpdate and returning false if it doesn't need to.

    Another way is to use React.PureComponent or stateless components. Pure and stateless components only re-render when there are changes to it's props.

提交回复
热议问题