Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How does React make sure that useEffect is called after the browser has had a chance to paint?

The documentation for useLayoutEffect says:

Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

the documentation for useEffect says:

Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event.

how does React check when the layout and paint has happened and when is the right time to call useEffect ? A hack that i have used often in to use setTimeout 0 for such scenarios, but i am interested in understanding how React implements this? (SetTimeout, requestAnimationFrame ?)

like image 550
gaurav5430 Avatar asked Jan 01 '23 21:01

gaurav5430


1 Answers

They use postMessage (in combination with requestAnimationFrame):

  // We use the postMessage trick to defer idle work until after the repaint.

Found in React/scheduler/src/forks/SchedulerHostConfig.default.js

setTimeout can't be used as it will be throttled if used recursively. requestAnimationFrame can't be used by itself as that gets triggered right before the repaint. Now if you however post a message to the page itself right before the repaint using postMessage, then that callback will run directly after the repaint.

 const channel = new MessageChannel();

 channel.port1.onmessage = function() {
  console.log("after repaint");
 };

 requestAnimationFrame(function () {
   console.log("before repaint");
   channel.port2.postMessage(undefined);
 });
like image 95
Jonas Wilms Avatar answered Jan 08 '23 00:01

Jonas Wilms