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 Dammic/93d2a30f34833661361fd5f1cb0fbfc7 to your computer and use it in GitHub Desktop.
Save Dammic/93d2a30f34833661361fd5f1cb0fbfc7 to your computer and use it in GitHub Desktop.
Bind in constructor vs bind in render
<div id="app"></app>
/*
* A simple React component
*/
class Application extends React.Component {
render() {
return <div>
<div>!!Check the console!!</div>
<div>Here you have an example why binding in render can be really bad for the performance of your applications.</div>
<div>Despite Clicker being a pure component, the function passed to it in props gets created anew each time a parent is rerendered, in case of binding a function in render. As the function is different, props passed to children are different, and the children rerender</div><br/>
<div>When we bind a function inside a constructor and then pass just the function to the Clicker, the props are still the same, so the component does not rerender</div>
<div className="container">
<BindedInRender/>
<BindedInConstructor/>
</div>
</div>;
}
}
class BindedInRender extends React.Component {
constructor() {
super()
this.state = {
index: 0
}
}
click() {
const {index} = this.state
this.setState({
index: index + 1
})
}
render() {
return <div>
Binded in render:
<Clicker clickText="(Render bind):I was rendered because props were different" onClick={this.click.bind(this)}/>
</div>;
}
}
class BindedInConstructor extends React.Component {
constructor() {
super()
this.state = {
index: 0
}
this.click = this.click.bind(this)
}
click() {
const {index} = this.state
this.setState({
index: index + 1
})
}
render() {
return <div>
Binded In constructor:
<Clicker clickText="(Constructor bind):I was rendered because props were different" onClick={this.click}/>
</div>;
}
}
class Clicker extends React.PureComponent {
render() {
const {clickText, onClick} = this.props
console.info(clickText)
return <div>
<button onClick={onClick}>click</button>
</div>;
}
}
ReactDOM.render(
<Application />,
document.getElementById('app')
);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@15.3.0/dist/react.min.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.0/dist/react-dom.min.js"></script>
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
max-width: 500px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment