最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
  • 2 I just figged through the react source, still I could not find the relevant part ... All I did find was ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED :) – Jonas Wilms Commented Jun 23, 2019 at 21:12
Add a comment  | 

1 Answer 1

Reset to default 24

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);
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论