Skip to content
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

An update on async rendering #596

Merged
merged 64 commits into from
Mar 27, 2018
Merged
Show file tree
Hide file tree
Changes from 50 commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
544c0bc
Migrated async update from Quip to Markdown
bvaughn Feb 6, 2018
e298b47
Wordsmithing
bvaughn Feb 6, 2018
9ff0f12
Split StrictMode into its own top level docs page
bvaughn Feb 6, 2018
0674c34
Added string ref section to strict mode page
bvaughn Feb 6, 2018
cdb4b9e
Added TOC header links to Strict Mode page
bvaughn Feb 6, 2018
289a2da
Prettier
bvaughn Feb 6, 2018
99fedea
Wording changes in response to PR feedback
bvaughn Feb 6, 2018
49464f7
Removed some unnecessary parens
bvaughn Feb 6, 2018
fe6b133
Add Dan as an author to "Update on Async"
bvaughn Feb 6, 2018
1314117
Wording improvements in response to Dan's feedback
bvaughn Feb 7, 2018
f005c04
Wordsmithing
bvaughn Feb 7, 2018
06d5be4
Prettier
bvaughn Feb 7, 2018
3696388
Increased Prettier line-width for examples
bvaughn Feb 7, 2018
ac23b1f
Trigger Netlify rebuild
bvaughn Feb 7, 2018
5cae7c6
Strict Mode blog title capitalization
bvaughn Feb 7, 2018
f70c0dd
Minor wordsmithing
bvaughn Feb 7, 2018
c1e67be
Wordsmithing in response to PR feedback
bvaughn Feb 12, 2018
75a43aa
Wordsmithing in response to PR feedback
bvaughn Feb 12, 2018
fb3b91f
Add explanation for render and commit lifecycles
bvaughn Feb 12, 2018
60d65ce
Wordsmithing
bvaughn Feb 12, 2018
f632f22
Wording changes for update-on-async and strict-mode
bvaughn Feb 13, 2018
626ac42
Moved StrictMode to docs rather than blog post
bvaughn Feb 13, 2018
7456327
Combined notes about react-lifecycles-compat
bvaughn Feb 13, 2018
2909738
Address more Sophie feedback
bvaughn Feb 13, 2018
5400338
Updated data-fetching example to show cWRP too
bvaughn Feb 13, 2018
813be17
Updated docs/recipes in response to a new GH question
bvaughn Feb 14, 2018
8de7dc4
Updated recipes to show updating/removing subscriptions
bvaughn Feb 16, 2018
c45fb40
Triggering rebuild of Netlify
bvaughn Feb 21, 2018
858c1a7
Fixed small error in example
bvaughn Feb 21, 2018
98d5a09
Added gDSFP to example
bvaughn Feb 21, 2018
442591c
Added example of updating subscription from props
bvaughn Feb 22, 2018
b1ce572
Typo
bvaughn Feb 23, 2018
2312173
Moved updating-subscription example into an external Gist with a note
bvaughn Feb 28, 2018
16eb646
Fixed typo
bvaughn Feb 28, 2018
4d16523
Typo
bvaughn Feb 28, 2018
9905159
Merge branch 'master' into update-on-async-rendering
bvaughn Mar 7, 2018
1ca6cfc
Moved async update blog post to a later, random date
bvaughn Mar 7, 2018
7408e07
Remoaved 'What can asynchronous rendering do?' section and instead li…
bvaughn Mar 7, 2018
3c75def
Deleted StrictMode and examples/images
bvaughn Mar 7, 2018
55650fc
Added explicit null value in state initializer
bvaughn Mar 15, 2018
97a109d
Added a note about experimental class properties usage in examples
bvaughn Mar 15, 2018
21fa116
Removed StrictMode from side nav
bvaughn Mar 16, 2018
92cf72d
Hardened wording a bit around async
bvaughn Mar 20, 2018
fa34fcf
16.4 -> 16.x
bvaughn Mar 22, 2018
b3bf0bd
Added getSnapshotBeforeUpdate recipe
bvaughn Mar 23, 2018
254fc8b
Wordsmithing nits
bvaughn Mar 23, 2018
b0c22f7
Wording tweak
bvaughn Mar 23, 2018
558d576
Reworked introduction
bvaughn Mar 24, 2018
7425aed
Typofix
bvaughn Mar 24, 2018
65b1496
Typo
bvaughn Mar 24, 2018
6eae811
Tweaks to async post
gaearon Mar 24, 2018
a2139de
Add a note about suspense
gaearon Mar 24, 2018
030980e
Merge pull request #6 from gaearon/tweaks-async-post
bvaughn Mar 24, 2018
e110ac5
Added a small TOC for examples
bvaughn Mar 24, 2018
ce060eb
Imported theme style tweaks from PR 587
bvaughn Mar 24, 2018
e143823
Added create-subscription example
bvaughn Mar 24, 2018
65eca09
Tweaks
bvaughn Mar 25, 2018
a3ea63a
Merge branch 'master' into update-on-async-rendering
bvaughn Mar 27, 2018
7ced9ce
Renamed blog post
bvaughn Mar 27, 2018
7cf5b58
Wordsmithing
bvaughn Mar 27, 2018
9f72403
Updated gradual migration note
bvaughn Mar 27, 2018
712f4de
Changed wording about app developer to React app developer
bvaughn Mar 27, 2018
4610392
Changes in response to Sophie's feedback
bvaughn Mar 27, 2018
b824bd2
Added getSnapshotBeforeUpdate to the polyfill notes
bvaughn Mar 27, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions content/blog/2018-03-15-update-on-async-rendering.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
title: Update on Async Rendering
author: [bvaughn]
---

For over a year, the React team has been working to implement asynchronous rendering. Last month during his talk at JSConf Iceland, [Dan unveiled some of the exciting new possibilities async rendering unlocks](/blog/2018/03/01/sneak-peek-beyond-react-16.html). Now we'd like to share with you some of the lessons we've learned while working on this feature, and some suggestions we have for preparing your components to be ready for async rendering when it launches.

One of the biggest lessons we've learned is that some of our legacy component lifecycles tend to encourage unsafe coding practices. They are:

* `componentWillMount`
* `componentWillReceiveProps`
* `componentWillUpdate`

These lifecycle methods have often been misunderstood and subtly misused; furthermore, we anticipate that their potential misuse may be more problematic with async rendering. Because of this, we will be adding an "UNSAFE_" prefix to these lifecycles in an upcoming release.

[React follows semantic versioning](/blog/2016/02/19/new-versioning-scheme.html), so this change will be gradual. Our current plan is:

* **16.3**: Introduce aliases for the unsafe lifecycles, `UNSAFE_componentWillMount`, `UNSAFE_componentWillReceiveProps`, and `UNSAFE_componentWillUpdate`. (Both the old lifecycle names and the new aliases will work in this release.)
* **16.x**: Enable deprecation warning for `componentWillMount`, `componentWillReceiveProps`, and `componentWillUpdate`. (Both the old lifecycle names and the new aliases will work in this release, but the old names will log a DEV-mode warning.)
* **17.0**: Remove `componentWillMount`, `componentWillReceiveProps`, and `componentWillUpdate` . (Only the new "UNSAFE_" lifecycle names will work from this point forward.)

Below, we will outline a migration plan for components that rely on these legacy lifecycles.

## Updating class components

#### If you're an application developer, **you don't have to do anything about the legacy methods yet**. The primary purpose of the upcoming version 16.3 release is to enable open source project maintainers to update their libraries in advance of any deprecation warnings. Those warnings will not be enabled until a future 16.x release.

However, if you'd like to start using the new component API (or if you're a maintainer looking to update your library in advance) here are a few examples that we hope will help you to start thinking about components a bit differently. Over time, we plan to add additional "recipes" to our documentation that show how to perform common tasks in a way that avoids the problematic lifecycles.

---

Before we begin, here's a quick overview of the lifecycle changes planned for version 16.3:
* We are adding the following lifecycle aliases: `UNSAFE_componentWillMount`, `UNSAFE_componentWillReceiveProps`, and `UNSAFE_componentWillUpdate`. (Both the old lifecycle names and the new aliases will be supported.)
* We are introducing two new lifecycles, static `getDerivedStateFromProps` and `getSnapshotBeforeUpdate`:

`embed:update-on-async-rendering/new-lifecycles-overview.js`

The new static `getDerivedStateFromProps` lifecycle is invoked after a component is instantiated as well as when it receives new props. It can return an object to update `state`, or `null` to indicate that the new `props` do not require any `state` updates.

The new `getSnapshotBeforeUpdate` lifecycle is called right before mutations are made (e.g. before the DOM is updated). The return value for this lifecycle will be passed as the third parameter to `componentDidUpdate`.

We'll look at examples of how both of these lifecycles can be used below.

> Note
>
> For brevity, the examples below are written using the experimental class properties transform, but the same migration strategies apply without it.

---

### Initializing state

This example shows a component with `setState` calls inside of `componentWillMount`:
`embed:update-on-async-rendering/initializing-state-before.js`

The simplest refactor for this type of component is to move state initialization to the constructor or to a property initializer, like so:
`embed:update-on-async-rendering/initializing-state-after.js`

### Fetching external data

Here is an example of a component that uses `componentWillMount` to fetch external data:
`embed:update-on-async-rendering/fetching-external-data-before.js`

The above code is problematic for both server rendering (where the external data won't be used) and the upcoming async rendering mode (where the request might be initiated multiple times).

The recommended upgrade path for most use cases is to move data-fetching into `componentDidMount`:
`embed:update-on-async-rendering/fetching-external-data-after.js`

There is a common misconception that fetching in `componentWillMount` lets you avoid the first empty rendering state. In practice this was never true because React has always executed `render` immediately after `componentWillMount`. If the data is not available by the time `componentWillMount` fires, the first `render` will still show a loading state regardless of where you initiate the fetch. This is why moving the fetch to `componentDidMount` has no perceptible effect in the vast majority of cases.

> Note
>
> Some advanced use-cases (e.g. libraries like Relay) may want to experiment with eagerly prefetching async data. An example of how this can be done is available [here](https://gist.github.com/bvaughn/89700e525ff423a75ffb63b1b1e30a8f).

### Adding event listeners (or subscriptions)

Here is an example of a component that subscribes to an external event dispatcher when mounting:
`embed:update-on-async-rendering/adding-event-listeners-before.js`

Unfortunately, this can cause memory leaks for server rendering (where `componentWillUnmount` will never be called) and async rendering (where rendering might be interrupted before it completes, causing `componentWillUnmount` not to be called).

People often assume that `componentWillMount` and `componentWillUnmount` are always paired, but that is not guaranteed. Only once `componentDidMount` has been called does React guarantee that `componentWillUnmount` will later be called for clean up.

For this reason, the recommended way to add listeners/subscriptions is to use the `componentDidMount` lifecycle:
`embed:update-on-async-rendering/adding-event-listeners-after.js`

> Note
>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of these notes, should we just plug create-subscription and then show an equivalent example with it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I think that's a reasonable change.

Copy link
Contributor Author

@bvaughn bvaughn Mar 24, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a stab at this. Let me know what you think?

It's a little awkward since create-subscription won't be released to NPM (and thus won't have a README) until we publish 16.3- so I had to link to the GitHub folder.

I also know there's some concern about over-promoting this package, since there are better solutions for some cases.

> Although the pattern above is slightly more verbose, it has an added benefit of deferring the subscription creation until after the component has rendered, reducing the amount of time in the critical render path. In the near future, React may include more tools to reduce code complexity for data fetching cases like this.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it has an added benefit of deferring the subscription creation until after the component has rendered, reducing the amount of time in the critical render path

I don't understand this setence. It seems to imply that componentDidMount doesn't block the initial render (which isn't true, and which I've observed to be a common misconception).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. Yeah, that's a good point. I'm not sure why I added that note. 😄


> Note
>
> Sometimes it is important to update subscriptions in response to property changes. If you're using a library like Redux or MobX, the library's container component should handle this for you. If you're authoring such a library, we suggest using a technique like [the one shown here](https://gist.github.com/bvaughn/d569177d70b50b58bff69c3c4a5353f3).

### Updating `state` based on `props`

Here is an example of a component that uses the legacy `componentWillReceiveProps` lifecycle to update `state` based on new `props` values:
`embed:update-on-async-rendering/updating-state-from-props-before.js`

Although the above code is not problematic in itself, the `componentWillReceiveProps` lifecycle is often mis-used in ways that _do_ present problems. Because of this, the method has been deprecated.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It hasn't been deprecated yet.


As of version 16.3, the recommended way to update `state` in response to `props` changes is with the new `static getDerivedStateFromProps` lifecycle. (That lifecycle is called when a component is created and each time it receives new props.):
`embed:update-on-async-rendering/updating-state-from-props-after.js`

> Note
>
> The [`react-lifecycles-compat`](https://github.com/reactjs/react-lifecycles-compat) polyfill enables this new lifecycle to be used with older versions of React as well. [Learn more about how to use it below.](http://localhost:8000/blog/2018/02/07/update-on-async-rendering.html#open-source-project-maintainers)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could be more explicit in this note that this only applies to library authors. Even though we already said it at the top I still anticipate people thinking they need to apply polyfill() in the application code.


### Invoking external callbacks

Here is an example of a component that calls an external function when its internal state changes:
`embed:update-on-async-rendering/invoking-external-callbacks-before.js`

Sometimes people use `componentWillUpdate` out of a misplaced fear that by the time `componentDidUpdate` fires, it is "too late" to update the state of other components. This is not the case. React ensures that any `setState` calls that happen during `componentDidMount` and `componentDidUpdate` are flushed before the user sees the updated UI. In general, it is better to avoid cascading updates like this, but in some cases they are necessary (for example, if you need to position a tooltip after measuring the rendered DOM element).

Either way, it is unsafe to use `componentWillUpdate` for this purpose in async mode, because the external callback might get called multiple times for a single update. Instead, the `componentDidUpdate` lifecycle should be used since it is guaranteed to be invoked only once per update:
`embed:update-on-async-rendering/invoking-external-callbacks-after.js`

### Updating external data when `props` change

Here is an example of a component that fetches external data based on `props` values:
`embed:update-on-async-rendering/updating-external-data-when-props-change-before.js`

The recommended upgrade path for this component is to move data-updates into `componentDidUpdate`. You can also use the new `getDerivedStateFromProps` lifecycle to clear stale data before rendering the new props:
`embed:update-on-async-rendering/updating-external-data-when-props-change-after.js`

> Note
>
> If you're using an HTTP library that supports cancellation, like [axios](https://www.npmjs.com/package/axios), then it's simple to cancel an in-progress request when unmounting. For native Promises, you can use an approach like [the one shown here](https://gist.github.com/bvaughn/982ab689a41097237f6e9860db7ca8d6).

### Reading DOM properties before an update

Here is an example of a component that reads a property from the DOM before an update in order to maintain scroll position within a list:
`embed:update-on-async-rendering/react-dom-properties-before-update-before.js`

In the above example, `componentWillUpdate` is used to read the DOM property. However with async rendering, there may be delays between "render" phase lifecycles (like `componentWillUpdate` and `render`) and "commit" phase lifecycles (like `componentDidUpdate`). If the user does something like resize the window during this time, the `scrollHeight` value read from `componentWillUpdate` will be stale.

The solution to this problem is to use the new "commit" phase lifecycle, `getSnapshotBeforeUpdate`. This method gets called _immediately before_ mutations are made (e.g. before the DOM is updated). It can return a value for React to pass as a parameter to `componentDidUpdate`, which gets called _immediately after_ mutations.

The two lifecycles can be used together like this:

`embed:update-on-async-rendering/react-dom-properties-before-update-after.js`

## Other scenarios

While we tried to cover the most common use cases in this post, we recognize that we might have missed some of them. If you are using `componentWillMount`, `componentWillUpdate`, or `componentWillReceiveProps` in ways that aren't covered by this blog post, and aren't sure how to migrate off these legacy lifecycles, please [file a new issue against our documentation](https://github.com/reactjs/reactjs.org/issues/new) with your code examples and as much background information as you can provide. We will update this document with new alternative patterns as they come up.

## Open source project maintainers

Open source maintainers might be wondering what these changes mean for shared components. If you implement the above suggestions, what happens with components that depend on the new static `getDerivedStateFromProps` lifecycle? Do you also have to release a new major version and drop compatibility for React 16.2 and older?

Fortunately, you do not!

In support of version 16.3, we've also created a new NPM package, [`react-lifecycles-compat`](https://github.com/reactjs/react-lifecycles-compat). This package polyfills components so that the new `getDerivedStateFromProps` lifecycle will also work with older versions of React (0.14.9+).

To use this polyfill, first add it as a dependency to your library:

```bash
# Yarn
yarn add react-lifecycles-compat

# NPM
npm install react-lifecycles-compat --save
```

Next, update your components to use the new static lifecycle, `getDerivedStateFromProps`, as described above.

Lastly, use the polyfill to make your component backwards compatible with older versions of React:
`embed:update-on-async-rendering/using-react-lifecycles-compat.js`
39 changes: 39 additions & 0 deletions examples/update-on-async-rendering/adding-event-listeners-after.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// After
class ExampleComponent extends React.Component {
// highlight-range{1-3}
state = {
subscribedValue: this.props.dataSource.value,
};
// highlight-line
// highlight-range{1-18}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

combine this with above highlight block too?

componentDidMount() {
// Event listeners are only safe to add after mount,
// So they won't leak if mount is interrupted or errors.
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);

// External values could change between render and mount,
// In some cases it may be important to handle this case.
if (
this.state.subscribedValue !==
this.props.dataSource.value
) {
this.setState({
subscribedValue: this.props.dataSource.value,
});
}
}

componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}

handleSubscriptionChange = dataSource => {
this.setState({
subscribedValue: dataSource.value,
});
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Before
class ExampleComponent extends React.Component {
// highlight-range{1-10}
componentWillMount() {
this.setState({
subscribedValue: this.props.dataSource.value,
});

// This is not safe; it can leak!
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);
}

componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}

handleSubscriptionChange = dataSource => {
this.setState({
subscribedValue: dataSource.value,
});
};
}
30 changes: 30 additions & 0 deletions examples/update-on-async-rendering/fetching-external-data-after.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// After
class ExampleComponent extends React.Component {
state = {
externalData: null,
};

// highlight-range{1-8}
componentDidMount() {
this._asyncRequest = asyncLoadData().then(
externalData => {
this._asyncRequest = null;
this.setState({externalData});
}
);
}

componentWillUnmount() {
if (this._asyncRequest) {
this._asyncRequest.cancel();
}
}

render() {
if (this.state.externalData === null) {
// Render loading state ...
} else {
// Render real UI ...
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Before
class ExampleComponent extends React.Component {
state = {
externalData: null,
};

// highlight-range{1-8}
componentWillMount() {
this._asyncRequest = asyncLoadData().then(
externalData => {
this._asyncRequest = null;
this.setState({externalData});
}
);
}

componentWillUnmount() {
if (this._asyncRequest) {
this._asyncRequest.cancel();
}
}

render() {
if (this.state.externalData === null) {
// Render loading state ...
} else {
// Render real UI ...
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// After
class ExampleComponent extends React.Component {
// highlight-range{1-4}
state = {
currentColor: this.props.defaultColor,
palette: 'rgb',
};
}
12 changes: 12 additions & 0 deletions examples/update-on-async-rendering/initializing-state-before.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Before
class ExampleComponent extends React.Component {
state = {};

// highlight-range{1-6}
componentWillMount() {
this.setState({
currentColor: this.props.defaultColor,
palette: 'rgb',
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// After
class ExampleComponent extends React.Component {
// highlight-range{1-8}
componentDidUpdate(prevProps, prevState) {
if (
this.state.someStatefulValue !==
prevState.someStatefulValue
) {
this.props.onChange(this.state.someStatefulValue);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Before
class ExampleComponent extends React.Component {
// highlight-range{1-8}
componentWillUpdate(nextProps, nextState) {
if (
this.state.someStatefulValue !==
nextState.someStatefulValue
) {
nextProps.onChange(nextState.someStatefulValue);
}
}
}
19 changes: 19 additions & 0 deletions examples/update-on-async-rendering/new-lifecycles-overview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Example extends React.Component<
Props,
State,
Snapshot
> {
static getDerivedStateFromProps(
nextProps: Props,
prevState: State
): $Shape<State> | null {
// ...
}

getSnapshotBeforeUpdate(
prevProps: Props,
prevState: State
): Snapshot {
// ...
}
}
Loading