React Class vs Hooks: Understanding 'this' Behavior

Why does this confuse people in React? Because it behaves very differently in classes vs hooks. 🧠 In React Class Components this refers to the component instance class Counter extends React.Component { state = { count: 0 }; increment() { this.setState({ count: this.state.count + 1 }); } render() { return <button onClick={this.increment}>+</button>; } } ❌ This breaks because this is lost in callbacks Fix it by: binding in constructor or using arrow functions increment = () => { this.setState({ count: this.state.count + 1 }); }; So in classes: this exists this must be bound correctly 🧠 In React Hooks (Functional Components) There is no this function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>+</button>; } Why? Functions don’t create component instances State is handled via closures No binding issues Much simpler mental model Hooks removed this from React because this was a common source of bugs, confusion, and boilerplate. If you understand this, React suddenly feels… calmer 😌 #reactjs #javascript #frontend #interviewprep

To view or add a comment, sign in

Explore content categories