What is the order of hooks in React 18?
Asked Answered
A

2

5

React 18 implements a new hook: useInsertionEffect.

So with useEffect and useLayoutEffect, what is the order of these 3 hooks at component generation ?

Angio answered 8/4, 2022 at 13:32 Comment(0)
G
13

According to the React Docs:

useInsertionEffect

It fires synchronously before all DOM mutations. Use this to inject styles into the DOM before reading layout in useLayoutEffect. So it runs before useLayoutEffect.

useLayoutEffect

It fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render.

useEffect

It will run after the render is committed to the screen. So it runs after useLayoutEffect.

Therefore the order of running is:

  1. useInsertionEffect
  2. useLayoutEffect
  3. useEffect
Glycosuria answered 10/4, 2022 at 6:50 Comment(0)
T
0

According to the new React Docs, i think maybe a little mistake has been made in the old document, because the new document says the execution timing of useInsertionEffect is not guaranteed, it may run either before or after the DOM has been updated. however, the order of these three hooks is totally right

Taffy answered 12/1 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.