-
Notifications
You must be signed in to change notification settings - Fork 558
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
async-safe, static lifecycle hooks #6
Changes from 3 commits
9818f57
839547f
b7189cc
aad6845
99988da
4a34d25
902d4b3
3df7ce6
1864c93
428758b
cfcb7e8
536084d
a1431a4
3c6132e
4425dbe
67272ce
c7f6728
bb2d246
8618f70
8f6c20e
e05e317
7042a2a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,258 @@ | ||
- Start Date: 2017-12-08 | ||
- RFC PR: (leave this empty) | ||
- React Issue: (leave this empty) | ||
|
||
# Summary | ||
|
||
Replace error-prone render phase lifecycle hooks with static methods to make it easier to write async-compatible React components. | ||
|
||
Provide a clear migration path for legacy components to become async-ready. | ||
|
||
# Basic example | ||
|
||
## Current API | ||
|
||
The following example combines several patterns that I think are common in React components: | ||
|
||
```js | ||
class ExampleComponent extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
|
||
this.state = { | ||
derivedData: null, | ||
externalData: null, | ||
someStatefulValue: null | ||
}; | ||
} | ||
|
||
componentWillMount() { | ||
asyncLoadData(this.props.someId).then(externalData => | ||
this.setState({ externalData }) | ||
); | ||
|
||
addExternalEventListeners(); | ||
|
||
computeMemoizeData(nextProps, nextState); | ||
} | ||
|
||
componentWillReceiveProps(nextProps) { | ||
this.setState({ | ||
derivedData: computeDerivedState(nextProps) | ||
}); | ||
} | ||
|
||
componentWillUnmount() { | ||
removeExternalEventListeners(); | ||
} | ||
|
||
componentWillUpdate(nextProps, nextState) { | ||
if (this.props.someId !== nextProps.someId) { | ||
asyncLoadData(nextProps.someId).then(externalData => | ||
this.setState({ externalData }) | ||
); | ||
} | ||
|
||
if (this.state.someStatefulValue !== nextState.someStatefulValue) { | ||
nextProps.onChange(nextState.someStatefulValue); | ||
} | ||
|
||
computeMemoizeData(nextProps, nextState); | ||
} | ||
|
||
render() { | ||
if (this.state.externalData === null) { | ||
return <div>Loading...</div>; | ||
} | ||
|
||
// Render real view... | ||
} | ||
} | ||
``` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. An alternative could look like this: class ExampleComponent extends React.Component {
static deriveStateFromProps(props, state, prevProps) {
if (prevProps === null || props.someValue !== prevProps.someValue) {
return {
derivedData: computeDerivedState(props)
};
}
// Return null to indicate no change to state.
return null;
}
} Derived state would be shallowly merged with the state specified in the constructor. // Somewhere in React
instance.state = Object.assign({},
instance.state,
instance.type.deriveStateFromProps(instance.props, instance.state, null)
); Are we sure we don't want this behavior? Pros:
Cons:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How about passing There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @j-f1 Structure still won't be full. So if you compare some deep references then need to check existing of property. It's uglier, slower and harder to type. class ExampleComponent extends React.Component {
static deriveStateFromProps(props, state, prevProps) {
if (prevProps.someValue && props.someValue.nested !== prevProps.someValue.nested) {
return {
derivedData: computeDerivedState(props)
};
}
// Return null to indicate no change to state.
return null;
}
} There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
I considered this. In some ways I like it, but I was really concerned about this:
And the idea of passing |
||
|
||
## Proposed API | ||
|
||
This proposal would modify the above component as follows: | ||
|
||
```js | ||
class ExampleComponent extends React.Component { | ||
constructor(props) { | ||
super(props); | ||
|
||
this.state = { | ||
derivedData: null, | ||
externalData: null, | ||
someStatefulValue: null | ||
}; | ||
} | ||
|
||
static deriveStateFromProps(props, state, prevProps) { | ||
// If derived state is expensive to calculate, | ||
// You can compare props to prevProps and conditionally update. | ||
return { | ||
derivedData: computeDerivedState(props) | ||
}; | ||
} | ||
|
||
static prefetch(props, state) { | ||
// Prime the async cache early. | ||
// (Async request won't complete before render anyway.) | ||
// If you only need to pre-fetch before mount, | ||
// You can conditionally fetch based on state. | ||
asyncLoadData(props.someId); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The example for There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The name is a reference to link |
||
} | ||
|
||
componentDidMount() { | ||
// Event listeners are only safe to add after mount, | ||
// So they won't leak if mount is interrupted or errors. | ||
addExternalEventListeners(); | ||
|
||
// Wait for earlier pre-fetch to complete and update state. | ||
// (This assumes some kind of cache to avoid duplicate requests.) | ||
asyncLoadData(props.someId).then(externalData => | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I know I'll mess this up somehow by not caching :) I really like the
This might not be technically possible, but would be very clear on where to do async work on load without the user having to resolve the result in the correct lifecycle. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Even if you don't cache the request though, your browser will! 😄 (Unless the response is flagged to expire immediately) We're thinking the use of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fair enough! |
||
this.setState({ externalData }) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code as is will trigger “cannot update n unmounted component” warning because it doesn’t cancel the fetch (or the callback) on unmounting. In user land people typically solve it by keeping an How does this approach address this problem, if it does at all? Seems like if we’re touching fetching it’s a good chance to make the API easier to use. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, Dan. I think this proposal is orthogonal to the "unmounted component" case. (It doesn't make it any easier or harder.) I tried to keep the example code here as concise as possible to avoid distracting from the proposed API changes but you're right to point out that it's probably not good to show an example that could trigger a warning. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added an inline comment about this for now 😄 Just to keep the before-and-after comparison as apples-to-apples as I can. |
||
); | ||
} | ||
|
||
componentDidUpdate(prevProps, prevState) { | ||
// Callbacks (side effects) are only safe after commit. | ||
if (this.state.someStatefulValue !== prevState.someStatefulValue) { | ||
this.state.onChange(this.state.someStatefulValue); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Whoops. Thanks. |
||
} | ||
} | ||
|
||
componentWillUnmount() { | ||
removeExternalEventListeners(); | ||
} | ||
|
||
render() { | ||
// Memoization that doesn't go in state can be done in render. | ||
// It should be idempotent and have no external side effects though. | ||
computeMemoizeData(this.props, this.state); | ||
|
||
if (this.state.externalData === null) { | ||
return <div>Loading...</div>; | ||
} | ||
|
||
// Render real view... | ||
} | ||
} | ||
|
||
``` | ||
|
||
# Motivation | ||
|
||
The React team recently added a feature flag to stress-test Facebook components for potential incompatibilities with our experimental async rendering mode ([facebook/react/pull/11587](https://github.com/facebook/react/pull/11587)). We enabled this feature flag internally so that we could: | ||
1. Identify common problematic coding patterns with the legacy component API to inform a new async component API. | ||
2. Find and fix async bugs before they impact end-users by intentionally triggering them in a deterministic way. | ||
3. Gain confidence that our existing products could work in async. | ||
|
||
I believe this GK confirmed what we suspected about the legacy component API: _It has too many potential pitfalls to be safely used for async rendering._ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "I believe this GK confirmed ..." was a little confusing for me as a non-Facebooker. I assume it's referring to the experiment y'all did, but took me a few beats to guess that. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah, thank you. I'll change this to use non-Facebook-specific terminology. |
||
|
||
## Common problems | ||
|
||
Some of the most common problematic patterns that were uncovered include: | ||
* **Initializing Flux stores in `componentWillMount`**. It's often unclear whether this is an actual problem or just a potential one (eg if the store or its dependencies change in the future). Because of this uncertainty, it should be avoided. | ||
* **Adding event listeners/subscriptions** in `componentWillMount` and removing them in `componentWillUnmount`. This causes leaks if the initial render is interrupted (or errors) before completion. | ||
* **Non-idempotent external function calls** during `componentWillMount`, `componentWillUpdate`, or `componentWillReceiveProps` (eg registering callbacks that may be invoked multiple times, initializing or configuring shared controllers in such a way as to trigger invariants, etc.) | ||
|
||
The [example above](#basic-example) attempts to illustrate a few of these patterns. | ||
|
||
## Proposal | ||
|
||
This proposal is intended to reduce the risk of writing async-compatible React components. | ||
|
||
It does this by removing many<sup>1</sup> of the potential pitfalls in the current API while retaining important functionality the API enables. I believe this can be accomplished through a combination of: | ||
|
||
1. Choosing lifecycle method names that have a clearer, more limited purpose. | ||
2. Making certain lifecycles static to prevent unsafe access of instance properties. | ||
|
||
<sup>1</sup> It is not possible to detect or prevent all side-effects (eg mutations of global/shared objects). | ||
|
||
# Detailed design | ||
|
||
## New static lifecycle methods | ||
|
||
### `static prefetch(props: Props, state: State): void` | ||
|
||
This method is invoked before `render` for both the initial render and all subsequent updates. It is not called during server rendering. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IIRC componentWillMount is called in SSR. Since componentWillMount is being deprecated and replaced with prefetch and prefetch is not called in server rendering, that means that there would be no lifecycle calls on the server any more, right? Have you looked into what use cases cWM is used for on the server? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. <facepalm emoji> I just totally missed that line. Sorry! |
||
|
||
The purpose of this method is to initiate asynchronous request(s) as early as possible in a component's rendering lifecycle. Such requests will not block `render`. They can be used to pre-prime a cache that is later used in `componentDidMount`/`componentDidUpdate` to trigger a state update. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Inspiration for this method comes from facebook/react#7671 (comment):
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It may be just me, but I find the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That seems reasonable but the whole prefetching thing is also really a micro-optimization. It's a power-feature. You can just do it in I think this touches on a bigger issue that it is hard to pass values between different life-cycles which needs a bigger API refactor. That said, I think it is better that it is awkward because in an async scenario you can be interrupted before Same thing for just any random rerender for any other reason since this will also be in the update path. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could there be a method, say This would also solve the issue of the unmounting component attempting to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sounds similar to what @philraj proposed here? I mentioned that I think it's also somewhat common for async requests to do things like dispatch Flux store actions on completion (rather than updating I find myself hesitant about the idea of baking handling of this async promise-resolution into React core for some reason. I can't put my finger on why exactly and so I don't trust my opinion yet. (Maybe I worry about potential complexity or confusion. Maybe the idea is just too new to me.) Edit Whoops. Looks like you already saw and responded to that thread. (I'm reading through notifications in chronological order, so I hadn't noticed.) |
||
|
||
Avoid introducing any side-effects, mutations, or subscriptions in this method. For those use cases, use `componentDidMount`/`componentDidUpdate` instead. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would consider pre-priming a cache (as was suggested in the sentence above) to be a side-effect, so I'm not sure this sentence means exactly what it currently says. Maybe it should say something more like "any non-idempotent side effects"? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great suggestion! Thanks. |
||
|
||
### `static deriveStateFromProps(props: Props, state: State, prevProps: Props): PartialState | null` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there a reason for switching from passing in There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can name the parameter |
||
|
||
This method is invoked before a mounted component receives new props. Return an object to update state in response to prop changes. | ||
|
||
Note that React may call this method even if the props have not changed. I calculating derived data is expensive, compare new and previous prop values to conditionally handle changes. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Typo: “If” |
||
|
||
React does not call this method before the intial render/mount and so it is not called during server rendering. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be ideal IMHO if we could somehow coalesce this use case for initial mount and updating props. It's common for me to pull out a function like this already so that I can call it both during mount and I haven't read through this in its entirety though, maybe that's addressed elsewhere. There are also some cases (much rarer) where I use an instance variable during this derivation process. So it'd be unfortunate not to have that there, but with async maybe there are pitfalls that I'm not aware of (I should read all of this through). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree I’d like to have this called on initial mount too. Curious to learn more why this was decided against here. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As proposed, the name for this method isn't clear about if it will render on mount or not. The Having it run on initial render would be a great feature add. Just today a dev on my team asked why we end up having so much similar logic in There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
It’s clear in retrospect because you already know it. In practice I see engineers expect it to fire on initial mount very often. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That's something I wouldn't have guessed. Thanks for the insight There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Setting an instance property ( There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I frequently see things in the constructor being side-effectful, like Promises, event emitters, accessing globals etc. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure, but initializing state via the constructor (or just as a class property, which is nicer still IMO) isn't a side effect. Again, maybe I'm misunderstanding what you're saying. Are you suggesting that we shouldn't recommend using the constructor for anything (even There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I’m suggesting we make the initilization of state pure by returning from a function given some props passed in as arguments. The constructor still needs to exist for side-effectual, non-pure operations such as binding methods of the class, creating class methods as instanve variables and calling There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't understand the benefit of removing |
||
|
||
## Deprecated lifecycle methods | ||
|
||
### `componentWillMount` -> `unsafe_componentWillMount` | ||
|
||
This method will log a deprecation warning in development mode recommending that users either rename to `unsafe_componentWillMount` or use the new static `prefetch` method instead. It will be removed entirely in version 17. | ||
|
||
### `componentWillUpdate` -> `unsafe_componentWillUpdate` | ||
|
||
This method will log a deprecation warning in development mode recommending that users either rename to `unsafe_componentWillUpdate` or use the new static `prefetch` method instead. It will be removed entirely in version 17. | ||
|
||
### `componentWillReceiveProps` -> `unsafe_componentWillReceiveProps` | ||
|
||
This method will log a deprecation warning in development mode recommending that users either rename to `unsafe_componentWillReceiveProps` or use the new static `deriveStateFromProps` method instead. It will be removed entirely in version 17. | ||
|
||
# Drawbacks | ||
|
||
The current component lifecycle hooks are familiar and used widely. This proposed change will introduce a lot of churn within the ecosystem. I hope that we can reduce the impact of this change through the use of codemods, but it will still require a manual review process and testing. | ||
|
||
This change is **not fully backwards compatible**. Libraries will need to drop support for older versions of React in order to use the new, static API. Unfortunately, I believe this is unavoidable in order to safely transition to an async-compatible world. | ||
|
||
# Alternatives | ||
|
||
## Try to detect problems using static analysis | ||
|
||
It is possible to create ESLint rules that attempt to detect and warn about potentially unsafe actions inside of render-phase lifecycle hooks. Such rules would need to be very strict though and would likely result in many false positives. It would also be difficult to ensure that library maintainers correctly used these lint rules, making it possible for async-unsafe components to cause problems within an async tree. | ||
|
||
Sebastian has also discussed the idea of side effect tracking with the Flow team. Conceptually this would enable us to know, statically, whether a method is free of side effects and mutations. This functionality does not currently exist in Flow though, and if it did there will still be an adoption problem. (Not everyone uses Flow and there's no way to gaurantee the shared components you rely on are safe.) | ||
|
||
## Don't support async with the legacy class component API | ||
|
||
We could leave the class component API as-is and instead focus our efforts on a new stateful, functional component API. If a legacy class component is detected within an async tree, we could revert to sync rendering mode. | ||
|
||
There are no advanced proposals for such a stateful, functional component API that I'm aware of however, and the complexity of such a migration would likely be at least as large as this proposal. | ||
|
||
# Adoption strategy | ||
|
||
Begin by reaching out to prominent third-party library maintainers to make sure there are no use-cases we have failed to consider. | ||
|
||
Assuming we move forward with the proposal, release (at least one) minor 16.x update to add deprecation warnings for the legacy lifecycles and inform users to either rename with the `unsafe_` prefix or use the new static methods instead. We'll then cordinate with library authors to ensure they have enough time to migrate to the new API in advance of the major release that drops support for the legacy lifecycles. | ||
|
||
We will provide a codemod to rename the deprecated lifecycle hooks with the new `unsafe_` prefix. | ||
|
||
We will also provide codemods to assist with the migration to static methods, although given the nature of the change, codemods will be insufficient to handle all cases. Manual verification will be required. | ||
|
||
# How we teach this | ||
|
||
Write a blog post (or a series of posts) announcing the new lifecycle hooks and explaining our motivations for the change, as well as the benefits of being async-compatible. Provide examples of how to migrate the most common legacy patterns to the new API. (This can be more detailed versions of the [basic example](#basic-example) shown in the beginning of this RFC.) | ||
|
||
# Unresolved questions | ||
|
||
## Can `shouldComponentUpdate` remain an instance method? | ||
|
||
Anectdotally, it seems far less common for this lifecycle hook to be used in ways that are unsafe for async. The overwhelming common usagee of it seems to be returning a boolean value based on the comparison of current to next props. | ||
|
||
On the one hand, this means the method could be easily codemodded to a static method, but it would be equally easy to write a custom ESLint rule to warn about `this` references to anything other than `this.props` inside of `shouldComponentUpdate`. | ||
|
||
Beyond this, there is some concern that making this method static may complicate inheritance for certain languages/compilers. | ||
|
||
## Can `render` remain an instance method? | ||
|
||
There primary motivation for leaving `render` as an instance method is to allow other instance methods to be used as event handlers and ref callbacks. (It is important for event handlers to be able to call `this.setState`.) We may change the event handling API in the future to be compatible with eg error boundaries, at which point it might be appropriate to revisit this decision. | ||
|
||
Leaving `render` as an instance method also provides a mechanism (other than `state`) on which to store memoized data. | ||
|
||
## Other | ||
|
||
Are there important use cases that I've overlooked that the new static lifecycles would be insufficient to handle? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adding event listeners in componentWillMount is a bug, right? I know that it would make SSR fail (since there's no DOM), and it seems like you say it's a problem in the Common Problems section. If that's right, a comment to that effect would be super helpful!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Flux stores are external event listeners that don't need a DOM, but also SSR alone is not necessarily that common. Especially for long tail.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, that's helpful context, but my question here is whether or not this line is currently considered a bug. It sounds like this document is saying yes, it is, although I'm not entirely sure. If so, I think a comment would help understanding. Does that make sense?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah. This is not a good pattern. (I listed it below as a common problem we see.) I show it here only to show where it should be done instead. I've added an inline comment to this part of the example though to make it clear that it's not a pattern we recommend. 😄