Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 componentDidMount or componentDidUpdate, 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 computation.
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 computation is running? If so, how can this be?

like image 298
cbdeveloper Avatar asked Jul 10 '19 10:07

cbdeveloper


1 Answers

Class Component

  1. Render the virtual dom.
  2. componentDidMount.
  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 componentDidMount and useEffect. (almost)
But if it is synchronous, componentDidMount and useLayoutEffect cause a visual lag.

like image 190
Jehong Ahn Avatar answered Nov 09 '22 12:11

Jehong Ahn