Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda