useEffect vs useLayoutEffect

Tram Ho

React Hook API (useEffect vs useLayoutEffect)

Both have similar spellings and are used to process effects. So what's the difference here? The difference is how they work.

Most of us use our own UseEffect. And one beautiful day I noticed when using the useEffect to set data initially instead of componentDidMount in the class component , the phenomenon of slight flickering was quite annoying.

You can see the demo here

useEffect

When moving from class component to function component , you will have to touch React Hook. useEffect replaces componentDidMount , componentWillUpdate , componentWillUnMount , and is often used to fetching data the results will not change immediately.

useEffect will be run after rendering the component . In the above example, when we click the button to change the value, the component will render, return the UI, then run useEffect, in useEffect we change the value of the state so react will re-render again to redraw. UI.

The order of implementation is as follows:

  1. You will cause an event (change state / props, re-render from parent component, …)
  2. Render component.
  3. Updated UI screen.
  4. Run useEffect.

In this case we should use useLayoutEffect

useLayoutEffect

If you see a jerky phenomenon, use it to measure position in the DOM (measure position of element, …) try useLayoutEffect . It is similar to useEffect but different from how it is run. useLayoutEffect will run before updating the UI.

The order of implementation is as follows:

  1. You will cause an event (change state / props, re-render from parent component, …)
  2. Render component.
  3. Run useLayoutEffect, and react will wait until it completes.
  4. Updated UI screen.

Editing using useLayoutEffect will have the following result:

This is the result we expected.

summary

  • useEffect : Will be the right choice, helping optimize the running speed from waiting for what is often used to fetching data .

  • useLayoutEffect : But if you want to handle synchronization with the UI, use useLayoutEffect

References:

https://kentcdodds.com/blog/useeffect-vs-uselayouteffect

https://kentcdodds.com/blog/useeffect-vs-uselayouteffect

Share the news now

Source : Viblo