Browse Source

Updated recipes to show updating/removing subscriptions

main
Brian Vaughn 7 years ago
parent
commit
8de7dc42ba
  1. 3
      content/blog/2018-02-07-update-on-async-rendering.md
  2. 53
      examples/update-on-async-rendering/adding-event-listeners-after-continued.js

3
content/blog/2018-02-07-update-on-async-rendering.md

@ -105,6 +105,9 @@ For this reason, the recommended way to add listeners/subscriptions is to use th
>
> 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.
You may also need to update subscriptions based on changes in `props`. In this case, you should also wait to _remove_ a subscription until `componentDidUpdate`. For example:
`embed:update-on-async-rendering/adding-event-listeners-after-continued.js`
### 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:

53
examples/update-on-async-rendering/adding-event-listeners-after-continued.js

@ -0,0 +1,53 @@
// After
class ExampleComponent extends React.Component {
// highlight-range{1-3}
state = {
subscribedValue: this.props.dataSource.value,
};
// highlight-line
// highlight-range{1-3}
componentDidMount() {
this.finalizeSubscription();
}
// highlight-line
// highlight-range{1-9}
componentDidUpdate(prevProps, prevState) {
if (this.props.dataSource !== prevProps.dataSource) {
// Similar to adding subscriptions,
// It's only safe to unsubscribe during the commit phase.
prevProps.dataSource.dispose();
this.finalizeSubscription();
}
}
componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}
// highlight-range{1-18}
finalizeSubscription() {
// Event listeners are only safe to add during the commit phase,
// So they won't leak if render 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,
});
}
}
handleSubscriptionChange = subscribedValue => {
this.setState({subscribedValue});
};
}
Loading…
Cancel
Save