j.doe
j.doe

Reputation: 1254

Why does my component re-render when a prop changes?

Whenever the value of animationType or animationComplete changes, the Splash component re-renders. I don't understand why it would re-render when there are no props passed into the render.

export class Splash extends React.Component {
    static propTypes = {
        animationType: allowNullPropType(PropTypes.string),
        animationComplete: PropTypes.bool,
        changeAnimation: PropTypes.func
    };

    componentDidMount() {
        const {changeAnimation} = this.props;

        // ...
    }

    componentDidUpdate() {
        const {animationType, animationComplete} = this.props;
        const shouldChangeScreen = (animationType === 'out' && animationComplete);

        if (shouldChangeScreen) {
            const {navigation} = this.props;

            // ...
        }
    }

    render() {
        return (
            <Fade id='splash' styles={styles.container}>
                <Logo height='125' width='125'/>
            </Fade>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        animationType: state.fade.getIn(['splash', 'type']),
        animationComplete: state.fade.getIn(['splash', 'complete'])
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        changeAnimation: (id, type) => dispatch(changeAnimation(id, type))
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Splash);

I have tried replacing the Fade (which is also connected to Redux store and dispatches actions) and Logo component with a simple View component and the problem still occurs. I have also tried using Reselect.

The only solution that works is:

shouldComponentUpdate() {
        return false;
    }

But that doesn't seem like a very good solution.

Upvotes: 0

Views: 93

Answers (2)

gazdagergo
gazdagergo

Reputation: 6721

You should always consider that "render" means "render the virtual DOM" in React. The actual DOM-part will only been re-rendered if something really changed. So no worries for the big number of renders.

Upvotes: 0

Maggie
Maggie

Reputation: 8101

That’s how react works. Any change in props will cause the component to call render method again, unless you prevent it with shouldComponentUpdate.

Upvotes: 2

Related Questions