Home > Mobile >  React useeffect shows mounting of component in 2 times
React useeffect shows mounting of component in 2 times

Time:04-17

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;

CodePudding user response:

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;

CodePudding user response:

It is because of React.StrictMode

You don't have to worry- just that StrictMode runs your effect code twice(only during development, don't have to worry about production) to be able to catch bugs and memory leaks among other things

Read more: https://reactjs.org/docs/strict-mode.html Screenshot here

CodePudding user response:

useEffect() equivalent with componentDidMount() and componentDidUpdate(). This means when rendering your component, useEffect() will be called twice. If you want useEffect() only called one time, you just add the second parameter for it. It will as this.

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

I hope this helpful for you!

  • Related