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

javascript - React hook useEffect() under the hood. Does an effect scheduled with useEffect block the main thread? - Stack Overf

programmeradmin0浏览0评论

In React DOCs, about the useEffect() hook, we get that:

"Effects scheduled with useEffect don’t block the browser from updating the screen."

Tip

Unlike ponentDidMount or ponentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen.

What does it mean by that exactly?

Example: Imagine that I have the following:

  • A controlled input
  • And a useEffect after 1st render that does some expensive synchronous putation.
function App() {
  const [inputValue,setInputValue] = React.useState('');

  useEffect(()=>{
    // RUN SOME EXPENSIVE SYNCHRONOUS FUNCTION
  },[]);

  return (
    <input value={inputValue} onChange={()=>setInputValue(event.target.value)}/>
  );

}

Does it mean that I would be perfectly able to use my input (which is controlled by React using JS, which is single-threaded) even when that heavy synchronous putation is running? If so, how can this be?

In React DOCs, about the useEffect() hook, we get that:

"Effects scheduled with useEffect don’t block the browser from updating the screen."

Tip

Unlike ponentDidMount or ponentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen.

What does it mean by that exactly?

Example: Imagine that I have the following:

  • A controlled input
  • And a useEffect after 1st render that does some expensive synchronous putation.
function App() {
  const [inputValue,setInputValue] = React.useState('');

  useEffect(()=>{
    // RUN SOME EXPENSIVE SYNCHRONOUS FUNCTION
  },[]);

  return (
    <input value={inputValue} onChange={()=>setInputValue(event.target.value)}/>
  );

}

Does it mean that I would be perfectly able to use my input (which is controlled by React using JS, which is single-threaded) even when that heavy synchronous putation is running? If so, how can this be?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jul 10, 2019 at 10:05 cbdevelopercbdeveloper 31.6k45 gold badges202 silver badges397 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Class Component

  1. Render the virtual dom.
  2. ponentDidMount.
  3. Paint to the browser.

Functional Component

  1. Render the virtual dom.
  2. useLayoutEffect.
  3. Paint to the browser.
  4. useEffect.

If your side effect is asynchronous, there is no difference between ponentDidMount and useEffect. (almost)
But if it is synchronous, ponentDidMount and useLayoutEffect cause a visual lag.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论