Sobes.tech
Junior — Middle

How can the lifecycle of a component in React be managed using the useEffect hook?

sobes.tech AI

Answer from AI

The useEffect hook in React allows you to manage the lifecycle of a functional component by performing side effects after rendering. It can be used for:

  • Executing code on component mount (similar to componentDidMount) when passing an empty dependencies array.
  • Updating the effect when specified dependencies change.
  • Cleaning up resources on component unmount (similar to componentWillUnmount) using a cleanup function.

Example:

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

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

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

    // Cleanup function, called on unmount
    return () => clearInterval(id);
  }, []); // empty array — effect runs once on mount

  return <div>Counter: {count}</div>;
}