Search code examples
reactjscomponentsuse-effect

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;

Solution

  • 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;