10

I created an all-new react app to test this myself because one of my friend was facing this issue. App.js code ->

function App() {

  useEffect(() => {
    console.log('on init gets called');
  }, []);

  return (
    <>
      Hello my first react app      
    </>
  );
}

export default App;

There is no other component present in the app. Following is the index.js code ->

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

console.log present in useEffect gets printed twice when we load the application for the first time. I want it to be printed only once.

Anubhav Gupta
  • 212
  • 2
  • 8
  • 3
    That's what's _supposed_ to happen: https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors – jonrsharpe Apr 13 '22 at 11:33
  • for me , it's run only once. maybe something else trigger another rendering... https://codesandbox.io/s/festive-shamir-s8tj7z?file=/src/App.js – yanir midler Apr 13 '22 at 12:41
  • 1
    for me also this happening exactly but by removing react strict mode in index.js issue cleared but why this happening in this project last created project not react like this @jonrsharpe thanks for for sharing – Hari Prasath S Apr 20 '22 at 04:08
  • 1
    It's because of React.StrictMode – farukbigez May 09 '22 at 14:34
  • You need to do this way: const isMounted = useRef(); useEffect(() => { if (!isMounted.current) return; isMounted.current = true; // ...rest of your code goes here... },[]) – CS Alam May 18 '22 at 16:13
  • 1
    https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount – Felix K. Jun 29 '22 at 01:14

1 Answers1

2

A tweak that worked for me -> Removed strict mode of react and it works normally. Not sure if there can be other solutions to this or why it was happening.

Anubhav Gupta
  • 212
  • 2
  • 8
  • 3
    const isMounted = useRef(); useEffect(() => { if (!isMounted.current) return; isMounted.current = true; // ...rest of your code goes here... },[]) – CS Alam May 18 '22 at 16:10
  • Removing StrictMode is the last thing to do. For a more detailed answer, see https://stackoverflow.com/questions/72238175/why-useeffect-running-twice-and-how-to-handle-it-well-in-react – Youssouf Oumar Dec 16 '22 at 14:57