Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
NextJS- How to execute some codes just once in useEffect in React.StrictMode children?

I have a problem. Im developing a nextJS app. React renders my components twice. I know it is because of StrictMode. But in React and nextJS document i found that they strongly suggest us to use StrictMode. But in a part of my app that i am working on, i use useEffect and i want some codes in useEffect run just once not twice! Because runing codes there twice, make a bad bug. So How can i do that? How can i do something to make react run some codes in useEffect once? And i placed [] as a dependency of useEffect but it didnt work! For example something like this:

`//inside a component that is a child of React.StrictMode
useEffect(() => {
/* strict mode cuses adding something to body twice. I want to add it just once and without using cleanup function */
document.body.appendChild(something)

//it runs twice, too. I dont want it!
console.log('test')
}, [])
`

Thanks for helping!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The general recommendation is that every effect should return a "cleanup" function, and the initial effect + cleanup should be a no-op (and thus effect->cleanup->effect = effect). In your case, you could remove the appended DOM node in the cleanup:

useEffect(() => {
const node = document.body.appendChild(something)
return () => document.body.removeChild(node);
}, [])

The goal of strict mode is to catch issues like this for future versions of react where effects may run twice in weird cases (React may unmount and remount the component, and the bug would appear).

about 4 years ago · Juan Pablo Isaza Report

0

What if you made something a dependent of the useEffect function so that it only runs it when that 'something' changes? Unfortunately rendering twice to flush out side effects is just how strict mode works and there isn't a good way around that. I don't really always use it though even though it is recommended, and I am a big nextjs user.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!