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 ?)
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 ?)
Share Improve this question asked Jun 23, 2019 at 20:26 gaurav5430gaurav5430 13.9k8 gold badges68 silver badges127 bronze badges 1 |1 Answer
Reset to default 24They 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);
});
ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
:) – Jonas Wilms Commented Jun 23, 2019 at 21:12