Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useeffect shows mounting of component in 2 times

i have a component names "Home" and i have a useEffect inside it which has a console.log("Home component mounted"). I just used a common useEffect hook. But when i initially render the page I getting the console log 2 times instead of showing it in the initial mounting of component. Can anyone tell me whats happening with my code. The code is as follows:

import React, { useEffect } from 'react';

const Home = () => {

  useEffect(()=>{
    console.log("Home component mounted")
  })

 return (
  <div className="container">
    <h1 className="h1">Home Page</h1>
  </div>
 )};

export default Home;
like image 432
Ren Jitsm Avatar asked Dec 10 '25 21:12

Ren Jitsm


1 Answers

It's happening because in your app in strict mode. Go to index.js and comment strict mode tag. You will find a single render.

This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.

Or you can try to use this hook : useLayoutEffect

import React, { useLayoutEffect } from "react";

const Home = () => {
  useLayoutEffect(() => {
    console.log("Home component mounted");
  }, []);

  return (
    <div className="container">
      <h1 className="h1">Home Page</h1>
    </div>
  );
};

export default Home;
like image 90
yanir midler Avatar answered Dec 13 '25 19:12

yanir midler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!