Skip to content

Discussion: componentWillReceiveProps vs getDerivedStateFromProps #721

@arieh

Description

@arieh

Hello

We have found a scenario where the removal of componentWillReceiveProps will encourage us to write worse code than we currently do.

We currently consider props to be a valid form of input and state for our component. If a component received a prop, we do not duplicate it into our state as to maintain a single source of truth. This is especially true when using state management libraries where the state is externalized from the component but will also be true for many other scenarios.

However, with the removal of componentWillReceiveProps, react will force us to use setState for any prop we would like to monitor for change. Basically, any type of prop change that would also trigger a following action (be it internal one or an external one) would require us to duplicate the prop into the state.

To give a sort of clean example, let's imagine a dialog that has a visible flag and would like to report when it was hidden to a logging framework. Currently, we can do:

componentWillReceiveProps(newProps){
      if (this.props.visible === true && newProps.visible === false) {
           registerLog('dialog is hidden'); 
      }
}

With the new paradigm, I will need to do:

static getDerivedStateFromProps(nextProps, prevState){
        if (this.state.visible === true && newProps.visible === false) {
           registerLog('dialog is hidden'); 
       }
        return {
               visible : nextProps.visible
        };
}

Aside from already duplicating the props, in my opinion this will heavily encourage users to do

static getDerivedStateFromProps(nextProps, prevState){
        return {
           ...prevState,
           ...props
        };
}

Since it takes away a lot of the usefulness of props.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions