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.

6
  • 3
    That's what's supposed to happen: reactjs.org/blog/2022/03/29/… Commented Apr 13, 2022 at 11:33
  • for me , it's run only once. maybe something else trigger another rendering... codesandbox.io/s/festive-shamir-s8tj7z?file=/src/App.js Commented Apr 13, 2022 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 Commented Apr 20, 2022 at 4:08
  • 1
    It's because of React.StrictMode Commented May 9, 2022 at 14:34
  • 1
    stackoverflow.com/questions/72238175/… Commented Jun 29, 2022 at 1:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

const isMounted = useRef(); useEffect(() => { if (!isMounted.current) return; isMounted.current = true; // ...rest of your code goes here... },[])
Removing StrictMode is the last thing to do. For a more detailed answer, see stackoverflow.com/questions/72238175/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.