Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Last active September 6, 2018 23:48
Show Gist options
  • Save ajcrites/630e7851ef244294e28000d15c9ec8a6 to your computer and use it in GitHub Desktop.
Save ajcrites/630e7851ef244294e28000d15c9ec8a6 to your computer and use it in GitHub Desktop.
// Bad Example
export class EndlessComponent extends React.Component<{ animate: boolean }, { animate: boolean }> {
componentDidUpdate() {
const animate = { this.props };
// This will trigger `componentDidUpdate` in an endless loop
// even if the value of `animate` does not change.
this.setState({ animate });
if (animate) {
doAnimate();
}
}
}
// Good Example
export class SaneComponent extends React.Component<{ animate: boolean }, { animate: boolean }> {
componentDidUpdate(prevProps) {
const animate = { this.props };
// Instead, compare the previous value. Only update state if necessary
// based on props
if (animate !== prevProps.animate) {
this.setState({ animate });
}
if (animate) {
doAnimate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment