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 ?)
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With