Last active
September 6, 2018 23:48
-
-
Save ajcrites/630e7851ef244294e28000d15c9ec8a6 to your computer and use it in GitHub Desktop.
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
// 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(); | |
} | |
} | |
} |
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
// 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