Class Lifecycle Methods

Class Example

Example

The same lifecycle in a class component.

import { Component, useState } from 'react';

class Clock extends Component {
  constructor(props) {
    super(props);
    this.state = { time: new Date().toLocaleTimeString() };
    console.log('constructor');
  }
  componentDidMount() {
    console.log('componentDidMount');
    this.timer = setInterval(() => this.setState({ time: new Date().toLocaleTimeString() }), 1000);
  }
  componentDidUpdate(prevProps) {
    if (prevProps.label !== this.props.label) console.log('componentDidUpdate: label changed');
  }
  componentWillUnmount() {
    console.log('componentWillUnmount');
    clearInterval(this.timer);
  }
  render() {
    return <p>{this.props.label}: {this.state.time}</p>;
  }
}

export default function App() {
  const [show, setShow] = useState(true);
  const [label, setLabel] = useState('Time');
  return (
    <div>
      <button onClick={() => setShow(!show)}>Toggle</button>
      <button onClick={() => setLabel(label === 'Time' ? 'Now' : 'Time')}>Change label</button>
      {show && <Clock label={label} />}
    </div>
  );
}

Result

Rarely Used Methods

MethodPurpose
static getDerivedStateFromPropsupdate state from props before render (rare)
shouldComponentUpdatereturn false to skip a re-render
getSnapshotBeforeUpdateread the DOM (e.g. scroll position) just before it changes
componentWillMount / WillReceiveProps / WillUpdatedeprecated (UNSAFE_ prefix)