class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.
I do not understand what is extra re-rendering. Can give me examples
In general, an event handler has the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus. Many objects also have methods that emulate events. For example, button has a click method that emulates the button being clicked.
Event handler properties Objects (such as buttons) that can fire events also usually have properties whose name is on followed by the name of the event. For example, elements have a property onclick . This is called an event handler property. To listen for the event, you can assign the handler function to the property.
Events are signals fired inside the browser window that notify of changes in the browser or operating system environment. Programmers can create event handler code that will run when an event fires, allowing web pages to respond appropriately to change.
Extra rerendring is rerendering when it is not necessary.
A component is rerendered when its props or state are changed. In the example, the child button component gets the callback as a prop.
Since the callback is recreated every time the parent component renders, the child/button component will rerender unnecessarily (the callback is always the same, but the way it is defined in the example causes it to be recreated as if it is different from its previous 'incarnation', in the previous render).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With