简体   繁体   中英

How does React measure DOM Elements in useLayoutEffect hook correctly before browser gets a chance to paint?

In the Official React docs, for useLayoutEffect, it is mentioned: The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

Also, in useLayoutEffect we are able to read the updated dimensions before the browser actually repaints.

How does react do that ?

If I am not mistaken, it works something like this:

  1. You click a button that updates the counter (for example).
  2. React updates the counter state.
  3. React updates the DOM (browser has not rendered it yet!).
  4. Browser renders the change.

The useLayoutEffect callback will be fired between steps 3 and 4.

Reason for this is that Browser calculate geometry of the layout and elements and takes into account css AND then goes to paint pixel by pixel on the screen.

Question is how layout hook is able to time running correctly between those steps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM