0

my useEffect Hook syntax:

useEffect(() => {
  let compeleteArray = allQuestion[questionIndex].incorrect_answers.push(
    allQuestion[questionIndex].correct_answer
  );
  setAllOptions(allQuestion[questionIndex].incorrect_answers);
  console.log(allQuestion[questionIndex].incorrect_answers);
  console.log("running");
  console.log(
    "addCorrect:",
    compeleteArray,
    "allQuestion.correct_answer:",
    allQuestion[questionIndex].correct_answer
  );
}, []);

Even I have define Empty Array for running once time !!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • if any other details of code needed for answering then please let me know, – Muzammil Raza Sep 29 '22 at 10:34
  • 1
    It might be because of Strict Mode .... can you see if `index.js` has this mode wrapped to `App` / `Main` component – KcH Sep 29 '22 at 10:36
  • 1
    I have rolled back your recent edit because 1) it invalidated the existing answer (once your question has received an answer, you're not allowed to fundamentally alter it), and 2) the new question you wrote is off-topic on Stack Overflow. It may be on-topic on [Super User](https://superuser.com/) or [Ask Ubuntu](https://askubuntu.com/), but do check their rules and expectations before posting. – Mark Rotteveel May 12 '23 at 09:23

1 Answers1

1

useEffect Run Twice in React v18

It happens only in development mode. If you want to disable it, you can remove strict mode in src/index.js. But that is not recommended.

In Production mode, the useEffect hook will run only once. To disable in development stage, you can do as follow

root.render(
//  <StrictMode> // comment this line
    <App />
//  </StrictMode> // and this this line
);

You can know more from here

Arman
  • 641
  • 4
  • 12