setState inside useLayoutEffect

Viewed 1588

As far as I understand it, useLayoutEffect runs synchronously, while useEffect asynchronously - more or less as if we used useLayoutEffect, but with setTimeout(func,0).

useLayoutEffect is meant to be used "whenever the effect's changing how the website looks". Therefore, I assume I should use it if, for example, the effect changes some state that's then later displayed to the user.

However, setState itself is asynchronous, which seems to defeat the synchronous purpose of useLayoutEffect - the UI change will be reflected in the DOM only in the next tick (unless we mutate the DOM directly, in an non-Reactish way).

What do I not understand correctly?

1 Answers

useLayoutEffect is meant to be used in cases where we need to read/write something from the DOM before that cycle is painted in the browser.

As you point, setState will update the value and trigger a new cycle, after the browser has been painted. Depending on the use of setState it might make sense to include it inside a useEffect or useLayoutEffect. For example if we were setting a value that we needed to read from the DOM before that cycle renders then it could make sense setState($ref.current.some_value_before_DOM_updates).

Related