What’s useEffect execution order and its internal clean-up logic when requestAnimationFrame and cancelAnimationFrame are used?

One thing that’s not clear in the above answers is the order in which the effects run when you have multiple components in the mix. We’ve been doing work that involves coordination between a parent and it’s children via useContext so the order matters more to us. useLayoutEffect and useEffect work in different ways in this regard.

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

useLayoutEffect runs the clean ups of each component (depth first), then runs the new effects of all components (depth first).

render parent
render a
render b
layout cleanup a
layout cleanup b
layout cleanup parent
layout effect a
layout effect b
layout effect parent
effect cleanup a
effect a
effect cleanup b
effect b
effect cleanup parent
effect parent
const Test = (props) => {
  const [s, setS] = useState(1)

  console.log(`render ${props.name}`)

  useEffect(() => {
    const name = props.name
    console.log(`effect ${props.name}`)
    return () => console.log(`effect cleanup ${name}`)
  })

  useLayoutEffect(() => {
    const name = props.name
    console.log(`layout effect ${props.name}`)
    return () => console.log(`layout cleanup ${name}`)
  })

  return (
    <>
      <button onClick={() => setS(s+1)}>update {s}</button>
      <Child name="a" />
      <Child name="b" />
    </>
  )
}

const Child = (props) => {
  console.log(`render ${props.name}`)

  useEffect(() => {
    const name = props.name
    console.log(`effect ${props.name}`)
    return () => console.log(`effect cleanup ${name}`)
  })

  useLayoutEffect(() => {
    const name = props.name
    console.log(`layout effect ${props.name}`)
    return () => console.log(`layout cleanup ${name}`)
  })

  return <></>
}

Leave a Comment