Created
March 1, 2018 16:43
-
-
Save peggyrayzis/0797e430d7cc81eef0dcde48c9115403 to your computer and use it in GitHub Desktop.
Async React low priority update component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
export class AsyncValue extends React.Component { | |
state = { asyncValue: this.props.defaultValue }; | |
deferSetState(state) { | |
ReactDOM.unstable_deferredUpdates(() => { | |
this.setState(state); | |
}); | |
} | |
componentDidMount() { | |
this.deferSetState((state, props) => ({ asyncValue: props.value })); | |
} | |
componentDidUpdate() { | |
if (this.props.value !== this.state.asyncValue) { | |
this.deferSetState((state, props) => ({ asyncValue: props.value })); | |
} | |
} | |
render() { | |
return this.props.children(this.state.asyncValue); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment