0

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?

6
  • Because putting logic unrelated to whether or not the component should update in sCU is misleading. It's called that for a reason. Commented Oct 23, 2019 at 0:02
  • I don't understand. The component should update (it's active state) on receiving prop Commented Oct 23, 2019 at 0:05
  • 1
    I think your misunderstanding the wording of the methods name. sCU isn’t “tell me what state properties should be updated”, it’s “tell me if the component should re-render given the current incoming state/props” Commented Oct 23, 2019 at 0:08
  • @bxyify Not only what Alexander said, but it would also be easy to create an infinite tender loop this way. Commented Oct 23, 2019 at 0:12
  • I thought it was a re-render when I change the state of an element? Commented Oct 23, 2019 at 0:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand this
@bxyify That's non-actionable. What don't you understand?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.