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

Viewed 392

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 ?

2 Answers

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?

Related