Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 = newMessageChannel();

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

 requestAnimationFrame(function () {
   console.log("before repaint");
   channel.port2.postMessage(undefined);
 });

Post a Comment for "React: How Does React Make Sure That Useeffect Is Called After The Browser Has Had A Chance To Paint?"