Class Components
Before Hooks arrived in React 16.8, Class Components were the only way to add
state and lifecycle logic to your UI. Understanding them is essential — you will encounter
them in real codebases, legacy projects, and interviews. In this chapter you will learn
the ES6 class syntax, how to use this.state
and this.setState(), what the
lifecycle methods are, how props work in class components, and when
class components still make sense today.
1. What is a Class Component?
A Class Component is a React component written as an
ES6 JavaScript class that extends React.Component.
It must include a render() method that returns JSX.
Before React 16.8 (2019), class components were the only way to manage state and run side effects. Today, functional components with Hooks are preferred — but class components still power millions of production apps and appear in every React interview.
render() method that returns JSX.
componentDidCatch
lifecycle method still only works in class components. If you need an Error Boundary,
you must write a class component (as of React 18).this.setState(), and the class/functional comparison
are standard React interview questions at every level — junior to senior.useEffect much easier to understand — because
useEffect was designed to replace lifecycle methods.
2. Class Component Syntax
Here is the minimum structure every class component must have:
import React, { Component } from 'react';
// Step 1: extend React.Component
class Greeting extends Component {
// Step 2: render() is required — returns JSX
render() {
return (
<div>
<h1>Hello from a class component!</h1>
</div>
);
}
}
export default Greeting;
Every class component has the same 4-part skeleton:
extends Component (or React.Component).super(props)
first, then initialise this.state and bind event
handlers.3. State & this.setState()
In a class component, state is a plain object stored on
this.state. You initialise it in the
constructor and always update it through
this.setState() — never by mutating
this.state directly.
import React, { Component } from 'react';
class Counter extends Component {
// 1. Initialise state in constructor
constructor(props) {
super(props); // ALWAYS call super(props) first
this.state = {
count: 0,
};
}
// 2. Update state with this.setState() — NEVER mutate directly
increment = () => {
this.setState({ count: this.state.count + 1 });
};
decrement = () => {
this.setState({ count: this.state.count - 1 });
};
// 3. Read state with this.state.propertyName
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>−</button>
</div>
);
}
}
export default Counter;
this.setState() does not update the state immediately.
React batches updates for performance. If your new state depends on the current state, always
use the updater function form:this.setState(prevState => ({ count: prevState.count + 1 }))This guarantees you always read the latest value, not a stale one.
// ❌ Risky when new state depends on old state
this.setState({ count: this.state.count + 1 });
// ✅ Safe — always use updater function for derived state
this.setState(prevState => ({
count: prevState.count + 1
}));
// Callback after state is applied (like useEffect with the value)
this.setState({ count: 10 }, () => {
console.log('State updated!', this.state.count); // 10
});
4. Props in Class Components
Props work the same way as in functional components — data flows from parent to child.
In a class component you access them via this.props
instead of a function parameter.
class WelcomeCard extends Component {
render() {
// Access props via this.props
const { name, role, city } = this.props;
return (
<div className="card">
<h2>Hello, {name}!</h2>
<p>Role: {role}</p>
<p>City: {city}</p>
</div>
);
}
}
// Usage — pass props like HTML attributes
<WelcomeCard
name="Priya"
role="React Developer"
city="Vadodara"
/>
props inside
constructor(), pass them to
super(props). Otherwise React won't set
this.props in the constructor body and you'll get
undefined if you try to read this.props there.
Outside the constructor, this.props always works fine.
class WelcomeCard extends Component {
render() {
return <h2>Hello, {this.props.name}!</h2>;
}
}
// Default props — used when the parent does not pass a prop
WelcomeCard.defaultProps = {
name: 'Guest',
};
// <WelcomeCard /> → "Hello, Guest!"
5. Lifecycle Methods
Every class component goes through three lifecycle phases: Mounting (component appears on screen), Updating (state or props changed), and Unmounting (component is removed). React calls specific methods at each stage — you override them to run your own logic.
this.state and bind methods. Call super(props) as the very first line.useEffect(..., []).true to allow
re-render, false to block it. Used for
manual performance optimisation — rarely needed in practice.useEffect.class DataLoader extends Component {
constructor(props) {
super(props);
this.state = { data: null, loading: true };
}
// ── MOUNT: fetch data after component is in the DOM ──
componentDidMount() {
fetch(`https://api.example.com/users/${this.props.userId}`)
.then(res => res.json())
.then(data => this.setState({ data, loading: false }));
}
// ── UPDATE: re-fetch when userId prop changes ─────────
componentDidUpdate(prevProps) {
if (prevProps.userId !== this.props.userId) {
this.setState({ loading: true });
fetch(`https://api.example.com/users/${this.props.userId}`)
.then(res => res.json())
.then(data => this.setState({ data, loading: false }));
}
}
// ── UNMOUNT: cancel anything that could leak ─────────
componentWillUnmount() {
console.log('DataLoader removed — clean up here');
}
render() {
if (this.state.loading) return <p>Loading…</p>;
return <pre>{JSON.stringify(this.state.data, null, 2)}</pre>;
}
}
6. Event Binding — Fixing the this Problem
The trickiest part of class components is event handler binding.
In JavaScript, regular class methods lose their this context
when passed
as a callback. You have three common solutions:
class BindingExamples extends Component {
constructor(props) {
super(props);
this.state = { msg: '' };
// Method 1 — bind in constructor (classic, works everywhere)
this.handleClick1 = this.handleClick1.bind(this);
}
handleClick1() {
this.setState({ msg: 'Bound in constructor' });
}
// Method 2 — class field arrow function (modern, most common ✅)
handleClick2 = () => {
this.setState({ msg: 'Arrow class field' });
};
render() {
return (
<div>
<button onClick={this.handleClick1}>Method 1</button>
<button onClick={this.handleClick2}>Method 2</button>
{/* Method 3 — inline arrow (avoid in real code — creates new fn every render) */}
<button onClick={() => this.setState({ msg: 'Inline arrow' })}>
Method 3
</button>
<p>{this.state.msg}</p>
</div>
);
}
}
this, and are supported by all modern
setups.
Avoid inline arrows in JSX (Method 3) if the component renders frequently, because a new
function is created on every render.
7. Class vs Functional — Same Counter, Two Styles
The best way to understand the difference is to build the same component both ways. Both produce identical output — the difference is in how much code you write:
class Counter extends Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState(prev => ({ count: prev.count + 1 }) ); }; render() { return ( <div> <p>{this.state.count}</p> <button onClick={this.increment} >+1</button> </div> ); } }
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>{count}</p> <button onClick={() => setCount(c => c + 1) } >+1</button> </div> ); }
| Feature | Class Component | Functional Component |
|---|---|---|
| Syntax | ES6 class extending Component | Plain JS function |
| State | this.state + this.setState() | useState() Hook |
| Side effects | componentDidMount/Update | useEffect() Hook |
| Hooks support | ✗ Not supported | ✓ Full support |
| Boilerplate | constructor, super, render() | None |
| this binding | Must bind event handlers | Not needed |
| Error Boundary | ✓ componentDidCatch works | ✗ Not available |
| Recommended for new code | Legacy only | ✓ Always |
8. When to Use Class Components
For any new code, always use functional components. The only cases where you still write a class component in 2024+ are:
componentDidCatch() and
getDerivedStateFromError() are only available in
class components. You need a class component to catch render errors in a subtree.
setState
async behaviour, and class vs functional differences. Knowing both styles gives
you a real advantage.
Explore More Tutorials
React.Component (or Component if imported), and
(2) the class must have a render() method that returns
JSX.
The constructor is optional — only needed if you want to initialise
this.state or bind methods. Everything else (lifecycle methods, class
fields)
is also optional.
super() before
using this. Without it, the JavaScript engine throws a
ReferenceError ("Must call super constructor before accessing 'this'").
Passing
props to super(props) ensures
this.props is available inside the constructor body.
If you call super() without props, this.props will be
undefined inside the constructor (though it works fine in other methods).
componentDidMount() runs once after the component mounts.
The functional equivalent is:
useEffect(() => { /* your code */ }, [])
The empty dependency array
[] tells React to run the effect
only once — after the first render — which mirrors
componentDidMount exactly.
Similarly:
•
componentDidUpdate → useEffect with dependencies
•
componentWillUnmount → cleanup function returned from
useEffect
this.setState(). If you mutate this.state directly
(e.g. this.state.count = 5), the state object changes in memory
but React never finds out — so the UI does not update.
Always use
this.setState() which: (1) merges your update into state,
(2) tells React a re-render is needed, and (3) batches multiple updates for performance.
- A Class Component is an ES6 class that
extends React.Componentand must have arender()method that returns JSX. - State is initialised in
constructor()asthis.state = {}. Always update viathis.setState()— never mutate directly. - Use the updater function form of setState (
setState(prev => ...)) when new state depends on old state, because setState is asynchronous. - Props are accessed via
this.props. Always callsuper(props)first in the constructor to makethis.propsavailable there. - Lifecycle phases: Mount (constructor → render → componentDidMount), Update (render → componentDidUpdate), Unmount (componentWillUnmount).
- Event handlers need to be bound to
this— use class field arrow functions for the cleanest approach. - Functional components with Hooks are preferred for all new code. Class components are still required for Error Boundaries and maintaining legacy code.
- Hook equivalents:
componentDidMount→useEffect(fn, []),componentWillUnmount→ cleanup return fromuseEffect.
<TodoList />
with state — then rewrite it as a functional component with useState.
Compare both side-by-side.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.