0
0
Reactframework~5 mins

Lifecycle mapping with hooks in React

Choose your learning style9 modes available
Introduction

Lifecycle mapping with hooks helps you run code at specific times in a React component's life, like when it starts or updates.

You want to fetch data when a component first appears on the screen.
You need to update the document title when some data changes.
You want to clean up timers or subscriptions when a component disappears.
You want to run code only once when the component loads.
You want to react to changes in specific data or props.
Syntax
React
useEffect(() => {
  // code to run
  return () => {
    // cleanup code
  };
}, [dependencies]);

useEffect runs after the component renders.

The dependencies array controls when the effect runs again.

Examples
This runs only once when the component first appears.
React
useEffect(() => {
  console.log('Runs once on mount');
}, []);
This runs every time the count value changes.
React
useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
This sets up a timer when the component mounts and cleans it up when it unmounts.
React
useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);
  return () => clearInterval(timer);
}, []);
Sample Program

This component counts seconds after it appears. It updates the page title with the count. The timer stops when the component disappears.

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

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    document.title = `Seconds: ${seconds}`;
  }, [seconds]);

  return (
    <div>
      <p>Seconds passed: {seconds}</p>
    </div>
  );
}

export default Timer;
OutputSuccess
Important Notes

Always clean up side effects like timers or subscriptions to avoid bugs.

Empty dependency array [] means run once on mount and clean on unmount.

Adding variables in dependencies runs effect when those variables change.

Summary

useEffect replaces lifecycle methods by running code after render.

Use dependencies to control when effects run again.

Clean up inside useEffect to avoid memory leaks.