The 'this' Binding Problem
You'll learn: Why class methods in React lose their this reference and how that breaks your component.
The Core Issue
In JavaScript classes, when you pass a method as a callback (like to onClick), the method loses its connection to this. React class components hit this problem constantly because you're always passing methods as event handlers.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
// ERROR! 'this' is undefined when called from onClick
}
render() {
return <button onClick={this.increment}>Add</button>;
}
}
When you click that button, you'll get: "Cannot read property 'setState' of undefined" — because this is undefined inside increment.
Why It Happens
Think of it like giving someone a page from a book without the cover. The page (method) doesn't know which book (component instance) it came from. JavaScript doesn't automatically remember the original object when you pass methods around.
The Three Fixes
1. Bind in constructor:
constructor(props) {
super(props);
this.increment = this.increment.bind(this);
}
2. Arrow function in render:
<button onClick={() => this.increment()}>Add</button>
3. Class field syntax (modern):
increment = () => {
this.setState({ count: this.state.count + 1 });
}
Arrow functions automatically capture this from their surrounding context, so they "remember" the component instance.
Key Takeaway: Class methods lose their this binding when passed as callbacks. You must explicitly bind them in the constructor, wrap them in arrow functions, or use class field arrow functions to maintain the correct context.