Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yeomann/62a8ea9b6ddd39fc8af541d980c920e5 to your computer and use it in GitHub Desktop.
Save yeomann/62a8ea9b6ddd39fc8af541d980c920e5 to your computer and use it in GitHub Desktop.
Advanced example for eagerly prefetching async data in a React component.
// This is an advanced example! It is not intended for use in application code.
// Libraries like Relay may make use of this technique to save some time on low-end mobile devices.
// Most components should just initiate async requests in componentDidMount.
class ExampleComponent extends React.Component {
_hasUnmounted = false;
state = {
externalData: null,
};
constructor(props) {
super(props);
// Prime an external cache as early as possible.
// Async requests are unlikely to complete before render anyway,
// So we aren't missing out by not providing a callback here.
asyncLoadData(this.props.someId);
}
componentDidMount() {
// Now that this component has mounted,
// Wait for earlier pre-fetch to complete and update its state.
// (This assumes some kind of external cache to avoid duplicate requests.)
asyncLoadData(this.props.someId).then(externalData => {
if (!this._hasUnmounted) {
this.setState({ externalData });
}
});
}
componentWillUnmount() {
this._hasUnmounted = true;
}
render() {
if (this.state.externalData === null) {
// Render loading state ...
} else {
// Render real UI ...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment