// Child component
class Button extends React.Component {
render() {
console.log("Render of Button called");
return (
<button onClick={this.props.handleClick}>
{this.props.children}
</button>
);
}
}
// Parent component
class ButtonRenderer extends React.Component {
state = {
count: 0
};
increment() {
this.setState({
count: this.state.count + 1
});
}
render() {
console.log("Render of ButtonRenderer called.");
return (
<div>
<Button handleClick={this.increment.bind(this)}>Click me</Button>
<div>Count: {this.state.count}</div>
</div>
);
}
}
function init() {
var rootElement = document.getElementById("root");
const childElement = <ButtonRenderer />;
ReactDOM.render(childElement, rootElement);
}
For every click of the button, state changes in parent component and hence ButtonRenderer.render will be called along with the child component, Button.render. Why?
I tried all 3 approaches for calling event handlers:
Using inline bind(). As in the above code.
Class property:
...
increment = () => {
this.setState({
count: ++this.state.count
});
}
...
<Button handleClick={this.increment}>Click me</Button>
...
- Inline arrow function.
...
increment(){
this.setState({
count: ++this.state.count
});
}
...
<Button handleClick={() => {this.increment();}}>Click me</Button>
...
For every click all 3 approaches exected both the render methods.
I expected approach1 and approach2 not to call Button's render method for every click as nothing changed. I expected approach3 to call Button's render method for every click as I am using inline arrow function which will create a new function for every render for ButtonRendered class.
Browser console output for every click of the button:
Render of ButtonRenderer called.
Render of Button called
My question: Why even approach1 (using bind) and approach2(using class properties) are calling render() method of child component Button when no pros have changed to Button comp?