Created
January 16, 2018 22:10
-
-
Save johnnyji/14edef82be2c2b93e6e71e073da4e6de to your computer and use it in GitHub Desktop.
Dirty Anon React Component
This file contains 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
class Main extends React.Component { | |
// ... | |
render() { | |
// We should NEVER pass anonymous functions as props to React components unless | |
// we absolutely need to. | |
// | |
// Anonymous functions are redefined on every render cycle, which means | |
// the function you pass to your child component is different every time. | |
// | |
// This will break shallow comparing on your child component, as the prop will be different every time. | |
return ( | |
<div> | |
<p>This button has been clicked {this.state.count} times</p> | |
<Button | |
label='Click me!' | |
onClick={() => this.setState({count: this.state.count + 1})} /> | |
</div> | |
); | |
} | |
} | |
// ... In another file ... | |
class Button extends React.Component { | |
// ... | |
shouldComponentUpdate(nextProps) { | |
// This will ensure that our component only ever re-renders | |
// if it's props have changed | |
return ( | |
this.props.onClick !== nextProps.onClick || | |
this.props.label !== nextProps.label | |
); | |
} | |
render() { | |
return <button onClick={this.props.onClick}>{label}</button>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment