3

I am a new learner of React. Currently, I am learning Hooks. I was studying about useEffect hook. It is mostly compared with the lifecycle methods (componentDidMount, componentDidUpdate, and componentWillUnmount, etc.). My question is about the behavior of these functions. Do the lifecycle methods run whether synchronously or asynchronously? What about useEffect?

Trevor
  • 13,085
  • 13
  • 76
  • 99
Muhammad Muaaz
  • 164
  • 1
  • 13

2 Answers2

1

Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously. In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect. You should go through the Documentation to have a clear view.

Mojo
  • 498
  • 1
  • 8
  • 16
  • Yes, I read it from the Documentation. Actually, this "Yellow Box" brought me here.It gives an intuition like class methods are synchronous whereas the hook method is asynchronous. – Muhammad Muaaz Nov 08 '19 at 11:47
1

As far as useEffect is concerned is runs asynchronously it works as this

You cause a render somehow (change state, or the parent re-renders)

React renders your component (calls it)

The screen is visually updated

THEN useEffect runs

React also has synchronous useEffect that is useLayoutEffect

You cause a render somehow (change state, or the parent re-renders)

React renders your component (calls it)

useLayoutEffect runs, and React waits for it to finish.

The screen is visually updated

You can read more about useLayoutEffect

Hope it helps

Community
  • 1
  • 1
ibtsam
  • 1,620
  • 1
  • 10
  • 10