Class Components: State & Lifecycle

Master the core of classic React. Learn how class components manage their own internal state and hook into the component lifecycle.

Lesson ProgressStep 1 of 9
My React App

Hello, world!

0 EXP

Hello! Let's build a React Class Component. This is the classic way to create stateful components.

class MyComponent extends React.Component {
  // We'll fill this in
}

The Class Component Blueprint

A class component is a JavaScript ES6 class that extends React.Component. This gives it access to React's features, like state and lifecycle methods.

The only method you **must** define is render(), which returns the JSX to be displayed.

If you need to initialize state or bind methods, you use the constructor(props). The first line inside it **must** be super(props), which calls the parent constructor and makes this.props available.

System Check

What is the only method required in a React class component?

Advanced Holo-Simulations

0 EXP

Log in to unlock these advanced training modules and test your skills.


Achievements

🏆
State Initiator

Correctly initialize state in a class component constructor.

🏗️
Lifecycle Architect

Correctly order the main class lifecycle methods.

✍️
State Setter Pro

Prove your mastery of `this.setState` syntax.

Mission: Build a Stateful Counter

Build a class component counter. It needs a `constructor` to initialize `this.state` with a `count` of 0. Then, create a method that uses `this.setState()` to increment the count, and wire it to the button's `onClick` event.

A.D.A. Feedback:

> System integrity looks stable. Code is valid.

Challenge: Order the Lifecycle

Drag these core lifecycle methods into the logical order they are called, from initialization to cleanup.

componentDidMount()
constructor()
componentWillUnmount()
render()
componentDidUpdate()

Challenge: Complete the Syntax

Fill in the missing parts to initialize and update state correctly.

class Counter extends React.Component {constructor(props) {super(props);count: 0 };}
increment = () => {count: + 1 });}}

Consult A.D.A.

Community Holo-Net

The Class Component Lifecycle: A Deep Dive

While modern React development heavily favors Functional Components and Hooks, understanding the Class Component lifecycle is crucial. You will encounter it in countless existing codebases, and its concepts form the foundation upon which Hooks were built. Furthermore, certain features like **Error Boundaries** can *still* only be implemented using Class Components.

The lifecycle is a sequence of methods that are automatically called at different phases of a component's existence. We can group these into three main phases: **Mounting**, **Updating**, and **Unmounting**.

Phase 1: Mounting (Birth)

These methods are called when an instance of a component is being created and inserted into the DOM.

  • constructor(props)

    The very first method called. This is the *only* place to initialize state directly (e.g., this.state = ...). You must call super(props)before anything else.

  • render()

    The only **required** method. It's a "pure" function that reads this.props and this.state and returns JSX. It should *not* contain side-effects (like API calls or setState).

  • componentDidMount()

    Called *after* the component is rendered to the DOM. This is the perfect place for **side-effects**:

    • Making API calls to fetch data.
    • Setting up subscriptions (e.g., timers, event listeners).
    • Interacting with the DOM directly.

Phase 2: Updating (Life)

An update can be triggered by a change in props or state. These methods are called when a component is being re-rendered.

  • shouldComponentUpdate(nextProps, nextState)

    A rare but powerful optimization tool. It runs *before* render(). If you return false, React will skip the re-render. By default, it always returns true.

  • render()

    Called again to generate the new JSX.

  • componentDidUpdate(prevProps, prevState)

    Called *after* the component re-renders. This is the place for side-effects that need to respond to a prop or state change. **Warning:** You must wrap any setStatecalls in a condition (e.g., if (this.props.userID !== prevProps.userID)) to avoid infinite loops.

🚨 The `setState` Asynchronicity Trap

Never assume `this.state` is updated immediately after calling this.setState(). React may batch multiple calls for performance.

// ❌ WRONG
this.setState({ count: this.state.count + 1 });
console.log(this.state.count); // Will log the OLD count

// ✅ CORRECT (using callback)
this.setState(
  { count: this.state.count + 1 },
  () => console.log(this.state.count) // Callback runs after update
);

// ✅ BEST (using function to avoid race conditions)
this.setState((prevState) => ({
  count: prevState.count + 1
}));

Phase 3: Unmounting (Death)

  • componentWillUnmount()

    Called right before a component is destroyed and removed from the DOM. This is the *only* place to perform **cleanup**:

    • Invalidate timers (e.g., `clearInterval`).
    • Remove event listeners.
    • Cancel API requests.
    Failing to clean up will cause **memory leaks**.

Key Takeaway: The Class Component lifecycle provides a robust set of "hooks" for managing side-effects, state, and performance. `constructor` for setup, `componentDidMount` for side-effects, `componentDidUpdate` for reacting to changes, and `componentWillUnmount` for cleanup are the essential methods you must know.

React Class Component Glossary

`React.Component`
The base class you must `extend` to create a React class component. It provides access to lifecycle methods and `this.state`.
`constructor()`
The class constructor. It's called before mounting. Used to initialize `this.state` and bind event handlers. Must call `super(props)` first.
`props`
Short for "properties". A read-only object of data passed *down* from a parent component. Accessed via `this.props`.
`state`
An object that is private to the component and fully controlled by it. Represents the component's internal "memory". A change in state triggers a re-render. Accessed via `this.state`.
`setState()`
The *only* correct way to update a component's state. It tells React to schedule a re-render. It is asynchronous and batches updates.
`render()`
The only **required** method in a class component. It must return the JSX that describes the component's UI. It should be a "pure" function of `this.props` and `this.state`.
`componentDidMount()`
Lifecycle method. Called once, *after* the component is added to the DOM. Ideal for API calls, setting up subscriptions, or DOM manipulation.
`componentDidUpdate()`
Lifecycle method. Called *after* a component re-renders due to changed props or state. Receives `prevProps` and `prevState` as arguments.
`componentWillUnmount()`
Lifecycle method. Called right *before* a component is removed from the DOM. Used for cleanup (e.g., clearing timers, removing event listeners) to prevent memory leaks.
Error Boundary
A special type of class component that implements `componentDidCatch()` or `static getDerivedStateFromError()`. It catches JavaScript errors anywhere in its child component tree and displays a fallback UI.

About the Author

Author's Avatar

TodoTutorial Team

Passionate developers and educators making programming accessible to everyone.

This article was written and reviewed by our team of web development experts, who have years of experience teaching React and building robust and accessible web applications.

Verification and Updates

Last reviewed: October 2025.

We strive to keep our content accurate and up-to-date. This tutorial is based on React v18 but covers the class component syntax relevant since React v16.

External Resources

Found an error or have a suggestion? Contact us!