Q1. Why do we need to bind event handlers in class components?
In JavaScript, class methods are not bound by default. If you pass a method as a callback (e.g., onClick={this.handleClick}), the 'this' context will be undefined when the method is called. Binding ensures 'this' refers to the component instance.
Q2. What are the ways to bind event handlers in class components?
You can bind in the constructor: this.handleClick = this.handleClick.bind(this). Use public class fields syntax: handleClick = () => { ... }. Or use arrow functions in render: onClick={() => this.handleClick()}. The last may cause performance issues as it creates a new function each render.
Q3. Do functional components need event binding?
No, functional components don't require binding because they use regular JavaScript functions that capture the correct 'this' from the lexical scope (or they don't use 'this' at all). You just define the function inside the component and use it directly.
Q4. What is the best practice for event binding in class components?
Using public class fields (arrow functions) is the most concise and avoids manual binding in the constructor. It ensures 'this' is correctly bound without extra performance cost.
Q5. What happens if you forget to bind an event handler?
When the event occurs, 'this' will be undefined (in strict mode) or window, causing errors like "Cannot read property 'setState' of undefined". Binding fixes this by setting the correct context.
