'Nextjs: set priority for useEffect

This is my _app.tsx

useEffect(() => {
    console.log(1)
}, []);

And this is my index.tsx

useEffect(() => {
    console.log(2)
}, []);

So, in my console print 21

But I want to print 12

How can I set priority for useEffect for run _app first?



Solution 1:[1]

Short Answer

You can't set priority across components.

Long Answer

Disregarding why someone would need control over the priority of useEffect across components in the first place, the order at which useEffect are being run by different component, cannot be controlled on our end. Following this article,

useEffect runs the clean up and the new effect before moving to the next component (depth) first and doing the same.

This means that children components will have there useEffect ran first, followed by its parent, which explains why the useEffect in index.tsx executes before app.tsx. This is because app.tsx can be seen as a container encompassing the whole app, making it the parent of any other component.

However, a possible workaround to control the order of a useEffect, is only by skipping a useEffect on first render by using a flag, further explained here.

const notInitialRender = useRef(false)
useEffect(() => {
  if (notInitialRender.current) {
    document.title = `Current count is ${count}`
  } else {
    notInitialRender.current = true
  }
}, [count])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1