15

Basically, I've got this pretty simple react component. What it does is, is wrap around 'react-intercom' and only render it if there is a change in the state. To simplify the question, I've hardwired the shouldCompoenentUpdate() method to always return false.

    import React from 'react';
    import Intercom from 'react-intercom';
    
    class IntercomWrapper extends React.Component {
        shouldComponentUpdate(nextProps, nextState) {
            // console.log(!!nextProps.user && nextProps.user.userId !== this.props.user.userId);
            // return !!nextProps.user && nextProps.user.userId !== this.props.user.userId;
            return false;
        }
    
        render() {
            console.log('rendering');
            return <Intercom {...this.props} />;
        }
    };
    
    export default IntercomWrapper;

What happens is that it always rerenders, which should not happen.

Anyone has any idea why would that happen?

vijay
  • 10,276
  • 11
  • 64
  • 79
bitstream
  • 1,108
  • 2
  • 19
  • 30
  • 2
    add console.log to `componentDidMount`, `componentWillUpdate` and `componentDidUpdate`see which one of them firing. If the component is unmounting and remounting shouldComponentUpdate won't work – bennygenel Sep 13 '17 at 12:16

3 Answers3

4

I figured it out eventually: The problem was that the wrapping component was receiving state changes, and was rerendering all children unconditionally (which is normal behaviour. It was a matter of rearranging components (getting this Intercom wrapper out of my <Layout> component). Thanks all for the help! Cheers!

bitstream
  • 1,108
  • 2
  • 19
  • 30
2

This wont prevent rendering of child components:
From the DOCS:

Returning false does not prevent child components from re-rendering when their state changes. ...

Note that in the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
0

If Intercom component renders when IntercomWrapper does not (because of shouldComponentUpdate being set to false), that means that Intercom component listens to data changes independently from {...this.props} passed from its parent (for example, it can be subscribed to a store).

I had the same problem, Child component was rendering when its Parent was not because of shouldComponentUpdate set to false. The reason was - Child was subscribed to store and listened to data changes independently from a parent.

magic_turtle
  • 1,243
  • 3
  • 17
  • 37