user6329530
user6329530

Reputation:

Why shouldn't I use shouldComponentUpdate in ReactJS?

Previously we used componentWillReceiveProps() to update a component on props change. Let's say have a component enable or disable an input field depending on some state in App.js

Now this is marked unsafe and

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Explains several alternatives to use instead.

But I wonder why none of these mention the use of shouldComponentUpdate() for this case. I could use

shouldComponentUpdate(nextProp){
    this.setState({
        active: nextProp.active
    });
    return true;
}

To set the state of the component active which removes the disabled from an input field.

From reading the docs I couldn't understand why they suggest rather complicated memoization helpers or the componentDidUpdate lifecycle (which only provides previousProbs and thus state that's older than the current state).

Is there a reason not to do it like in my example?

Upvotes: 0

Views: 452

Answers (1)

Matt
Matt

Reputation: 3642

shouldComponentUpdate is used in the case that a prop change is causing a re-render that you don't want - you may only care about certain props that affect the rendered view. You can manually inspect nextProps for changes to those specific props and decide to render or not.

You should not modify state (or anything else) inside of shouldComponentUpdate.

Upvotes: 3

Related Questions