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!
CodePudding user response:
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).
CodePudding user response:
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.