Trace why a React component is re-rendering

后端 未结 6 1906
傲寒
傲寒 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条回答
  •  难免孤独
    2020-12-04 05:04

    @jpdelatorre's answer is great at highlighting general reasons why a React component might re-render.

    I just wanted to dive a little deeper into one instance: when props change. Troubleshooting what is causing a React component to re-render is a common issue, and in my experience a lot of the times tracking down this issue involves determining which props are changing.

    React components re-render whenever they receive new props. They can receive new props like:

    or if MyComponent is connected to a redux store:

    function mapStateToProps (state) {
      return {
        prop3: state.data.get('savedName'),
        prop4: state.data.get('userCount')
      }
    }
    

    Anytime the value of prop1, prop2, prop3, or prop4 changes MyComponent will re-render. With 4 props it is not too difficult to track down which props are changing by putting a console.log(this.props) at that beginning of the render block. However with more complicated components and more and more props this method is untenable.

    Here is a useful approach (using lodash for convenience) to determine which prop changes are causing a component to re-render:

    componentWillReceiveProps (nextProps) {
      const changedProps = _.reduce(this.props, function (result, value, key) {
        return _.isEqual(value, nextProps[key])
          ? result
          : result.concat(key)
      }, [])
      console.log('changedProps: ', changedProps)
    }
    

    Adding this snippet to your component can help reveal the culprit causing questionable re-renders, and many times this helps shed light on unnecessary data being piped into components.

提交回复
热议问题