0
0
Reactframework~5 mins

Mounting phase in React

Choose your learning style9 modes available
Introduction

The mounting phase is when a React component is created and added to the screen for the first time. It helps show content to users.

When you want to display a new part of your app on the screen.
When you need to set up data or start timers as soon as a component appears.
When you want to fetch information from the internet right after showing a component.
When you want to prepare something only once before the user interacts with the component.
Syntax
React
useEffect(() => {
  // code to run on mount
}, []);

The empty array [] means this runs only once when the component appears.

This replaces older class methods like componentDidMount.

Examples
This logs a message once when the component first shows.
React
import React, { useEffect } from 'react';

function Welcome() {
  useEffect(() => {
    console.log('Component mounted');
  }, []);

  return <h1>Hello!</h1>;
}
This fetches data only once when the component mounts.
React
useEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => console.log(data));
}, []);
Sample Program

This component shows seconds passed since it appeared. It starts a timer when mounted and cleans it up when removed.

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); // cleanup on unmount
  }, []);

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

export default Timer;
OutputSuccess
Important Notes

Always clean up timers or subscriptions in the return function inside useEffect to avoid bugs.

The mounting phase happens only once per component instance.

Summary

The mounting phase is when a component first appears on screen.

Use useEffect with an empty array [] to run code only once on mount.

This is useful for setup tasks like fetching data or starting timers.