Using Hooks for advanced effects
There are two special versions of the Effect Hook: the Layout Effect Hook and the Insertion Effect Hook. These are only needed for very specific use cases, so we are only briefly covering them here.
useLayoutEffect
The Layout Effect Hook is identical to the Effect Hook, but it fires synchronously after all DOM mutations are completed and before the component is rendered in the browser. It can be used to read information from the DOM and adjust the appearance of components before rendering. Updates inside this Hook will be processed synchronously before the browser renders the component.
Do not use this Hook unless it is really needed, which is only in certain edge cases. useLayoutEffect
will block visual updates in the browser, and thus, is slower than useEffect
.
The rule here is to use useEffect
first. If your mutation changes the appearance of the DOM node, which can cause it to flicker, you should use useLayoutEffect
instead.