Skip to content

Legacy lifecycle use-case for componentWillReceiveProps #729

Closed
@timroes

Description

@timroes

In your update on async rendering blog post are a lot of examples on how to replace legacy lifecycle use-cases by the new methods. I am lacking an example for the following use-case: Change state depending on prop changes/diffs.

In contrast to the "Updating state based on props" which just looks into the new props and the previous state, I would like to see an example for a state change, that will require to look into the new and old properties - or an explanation why this is an anti-pattern.

A typical use-case I've seen often (and also used myself often) is, that I check within componentWillReceiveNewProps whether a specific property has changed from previous properties to new and if so change a state. I didn't save the previous property in the state (which I see how that would work with getDerivedStateFromProps, because it's never changed within the component or considered a "state" of the component).

A simple example of a tab container:

class TabContainer extends Component {

  state = {
    selectedTab: 0
  };

  componentWillReceiveNewProps(newProps) {
    if (newProps.tabs !== this.props.tabs) {
      // Reset selected tab if the tabs changed.
      // Though this could be a more sofisticated implementation, that keeps
      // the tab selected, if it still exists in the new tabs array, and only
      // resets to 0 if that tab doesn't exist anymore.
      this.setState({
        selectedTab: 0
      });
    }
  }

  /* Methods that change state.selectedTab when a specific tab is clicked. */

  renderTab = (tab, index) => {
    const active = this.state.selectedTab === index;
    return (/* tab depending on active state */);
  };

  render() {
    return (<div>
      <ul>
        { this.props.tabs.map(this.renderTab) }
      </ul>
      { /* selected tab content */ }
    </div>);
  }
}

TabContainer.propTypes = {
  tabs: PropTypes.array.isRequired,
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions