Sobes.tech
Middle+

What is the lifecycle of a component? What lifecycle methods do you know, use, and apply?

sobes.tech AI

Answer from AI

The lifecycle of a React component describes the sequence of stages from creation to removal from the DOM. The main lifecycle methods I use and know include:

  • constructor(props) — initializing state and binding methods.
  • componentDidMount() — called after the component is mounted, suitable for API requests or subscribing to events.
  • shouldComponentUpdate(nextProps, nextState) — allows optimizing rendering by returning true or false.
  • componentDidUpdate(prevProps, prevState) — called after updates, can react to prop or state changes.
  • componentWillUnmount() — cleaning timers, unsubscribing from events.

In functional components with hooks, the lifecycle is managed through useEffect, which can mimic componentDidMount, componentDidUpdate, and componentWillUnmount behaviors.

Example with useEffect hook:

import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);

    return () => clearInterval(id); // cleanup on unmount
  }, []); // empty array means effect runs once on mount

  return <div>Seconds passed: {count}</div>;
}
What is the lifecycle of a component? What lifecycle… - sobes.tech