0

I am rendering a simple react app component but I am not able to understand why "Inside useeffect hook." is being printed on console twice. Should it not just be printed once after the component is rendered, since there is no state change and the dependency array is also empty? Below is the code: `

export default function App(){
    const [count, setCount] = React.useState(0);
    useEffect(()=>{
        console.log("Inside useeffect hook.")
    },[]);

    return(
        <h1>hey.</h1>
    );
}

`

Paras
  • 1

3 Answers3

0

This is expected behavior of StrictMode added in React 18. You can read about it here in the docs. It unmounts and mounts again every component when it's mounted for the first time (only in dev environment), that's why your useEffect callback gets called twice

Marat
  • 618
  • 1
  • 6
  • 10
0

When we create our React app, using npx create-react-app, it creates our project with React.StrictMode. In the index.js file you can see this,

root.render(<React.StrictMode><App /></React.StrictMode>);

Just Remove the React.StrictMode and it will solve your problem.

root.render(<><App /></>);
0

remove React.StrictMode in the index.js file

react strictMode only work in develop env

see more infor: https://reactjs.org/docs/strict-mode.html

DEVNTV
  • 1
  • 1