Skip to content

Using Lifecycle with ES6 classes #2364

@taion

Description

@taion

It seems like a number of our users are complaining about finding it difficult to set up routerWillLeave hooks when using ES6 classes.

Personally, I think the right thing to do is to either suck it up and re-implement the code from the Lifecycle mixin, or drop back to React.createClass.

However, there's another option that's viable here that we'd be remiss not to consider. We could add something like a LifecycleWrapper class. The API would look something like:

render() {
  return (
    <LifecycleWrapper onLeave={this.onLeave}>
      {/* Whatever the component was going to render anyway */}
    </LifecycleWrapper>
  );
}

The benefit of doing it this way is that the onLeave hook will have access to e.g. state and props on the current component, in a very similar way to routerWillLeave on the Lifecycle mixin, while also freeing the user from explicitly managing the listener's lifecycle.

What do y'all think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature-requestUsed to close PRs that haven't gone through/been accepted the Proposal process yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions