Skip to content

What Are State and Lifecycle in React?

"State" and "lifecycle" are two important concepts in React and play a key role in building modern web applications.

  1. State:

    1. Definition: State is the data a React component holds at a given moment. It can change as a result of user interaction or over time.
    2. Example: Think of a form component: the text the user types can be kept in the component's state, so its appearance and behaviour can follow the input.
    3. How it works: In class components, state is usually initialised in the constructor and updated with this.setState. Changing the state re-renders the component.
  2. Lifecycle:

    1. Definition: Lifecycle methods are special methods called at different stages of a component's life, from creation to removal. They control how the component behaves and when it updates.
    2. Example methods:
      1. componentDidMount: Called right after the component is added to the DOM. Typically used for API calls and subscriptions.
      2. componentDidUpdate: Called when the component updates (for example after receiving new props or a state change).
      3. componentWillUnmount: Called right before the component is removed from the DOM; clean-up such as cancelling subscriptions happens here.
    3. How it works: Lifecycle methods are defined in the component class, and React calls them automatically at the right moment.

Together these two concepts are cornerstones of component-based development and give you the flexibility to build dynamic, interactive interfaces: state manages a component's inner data, lifecycle methods manage its life.

In function components: useState and useEffect

this.setState and the lifecycle methods above belong to class components. Since React 16.8, Hooks let function components do the same: state is kept with useState, and useEffect covers the work of componentDidMount, componentDidUpdate and componentWillUnmount.

React (JSX)
import { useState, useEffect } from 'react';

function Clock() {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    // componentDidMount: start the timer
    const timerId = setInterval(() => setDate(new Date()), 1000);
    // componentWillUnmount: clear the timer
    return () => clearInterval(timerId);
  }, []);

  return <h2>Time: {date.toLocaleTimeString('en-GB')}</h2>;
}

The clock updates every second. The function returned from useEffect runs when the component is removed and clears the timer.

Have a question about this article? Write to me