Navigate
Search topics, hooks, and fundamentals
this is a shape shifter β it becomes whatever called it. Arrow functions freeze its form forever. Understanding this is key to reading React code confidently.
π‘ Arrow functions and closures replaced the this binding nightmare. Understanding both is why modern React code just works.
These are the patterns that trip up developers most often. Switch between Wrong and Fixed to compare the code side by side.
class Timer {
constructor() {
this.seconds = 0;
}
tick() {
this.seconds++; // 'this' is undefined here!
console.log(this.seconds);
}
start() {
setInterval(this.tick, 1000); // passes reference, loses this
}
}const person = {
name: "Alice",
// Arrow function captures outer this (window/undefined)
greet: () => {
console.log(`Hi, I'm ${this.name}`); // this is NOT person!
},
};
person.greet(); // "Hi, I'm undefined"class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isOn: false };
// Forgot to bind handleClick!
}
handleClick() {
// TypeError: Cannot read property 'setState' of undefined
this.setState({ isOn: !this.state.isOn });
}
render() {
return <button onClick={this.handleClick}>Toggle</button>;
}
}