Skip to main content

Class Components and Lifecycle Methods

A class component is a class that extends Component and has a render() method. State is kept in this.state and updated with this.setState(), and lifecycle methods are used instead of hooks. It is a legacy API: new code uses function components. The only common feature that still needs a class is an error boundary.

Details​

Lifecycle Methods​

PhaseMethodPurposeWith hooks
Mountconstructor(props)Initialize stateuseState(initialValue)
MountcomponentDidMount()Subscribe, fetch, read the DOMuseEffect(fn, [])
UpdateshouldComponentUpdate(nextProps, nextState)Skip a re-rendermemo
UpdategetSnapshotBeforeUpdate(prevProps, prevState)Read the DOM before it changes (scroll position)No equivalent
UpdatecomponentDidUpdate(prevProps, prevState, snapshot)React to changed props or stateuseEffect(fn, [deps])
UnmountcomponentWillUnmount()Unsubscribe, clear timersThe cleanup function of useEffect
Anystatic getDerivedStateFromProps(props, state)Derive state from props (rarely needed)Compute during render
Errorstatic getDerivedStateFromError(error)Switch to a fallback UINo equivalent
ErrorcomponentDidCatch(error, info)Log the errorNo equivalent
  • render() runs on mount and on every update, between the methods above. It must be pure.
  • Methods before render belong to the render phase, componentDid… and componentWillUnmount to the commit phase, see Rendering.
  • componentWillMount, componentWillReceiveProps and componentWillUpdate are deprecated and renamed to UNSAFE_…; the old names still work with a warning.

Differences from Function Components​

  • this.setState merges the object into the state; a useState setter replaces the value.
  • Methods passed as handlers lose this, so they are declared as arrow class fields or bound in the constructor.
  • this.props and this.state are mutable and always the latest; a function component captures the values of its render.
  • Classes can't use hooks. Logic was shared with HOCs and render props.
  • PureComponent adds a shallow comparison of props and state, like memo.

A function component has no lifecycle methods. It goes through the same stages with effects: the setup runs after mount and after every update with changed dependencies, the cleanup runs before the next setup and on unmount.

Example​

import { Component } from 'react';

export default class Timer extends Component {
state = { seconds: 0 };

componentDidMount() {
this.intervalId = setInterval(this.tick, 1000);
}

componentWillUnmount() {
clearInterval(this.intervalId);
}

tick = () => {
this.setState((prevState) => ({ seconds: prevState.seconds + 1 }));
};

render() {
return <p>Seconds: {this.state.seconds}</p>;
}
}

See Also​