Home > Software design >  make useEffect run before render is completed OR an alternative to use Effect
make useEffect run before render is completed OR an alternative to use Effect

Time:07-19

I have functions that I want to execute when state changes. But I don't want them to wait until render is completed, since it doesn't depend on the rendered DOM.

Is there a way to execute a function when certain dependencies change just like useEffect, but not wait until rendering is completed?

I was thinking to use useMemo or useCallback, but it seems not an ideal solution since it uses memory.

Is there a direct solution for this?

CodePudding user response:

If the code that you want to execute may call state setters itself, which results in undesirable flickering, you can switch out useEffect for useLayoutEffect, which runs after the DOM mutations from the render have occurred, but before the browser has repainted the screen. As a result, if any state setters get called, and the component renders again, the user won't see the component rendering twice, because the updates all occur before the screen repainting (except for the very last one).

useLayoutEffect has the exact same function signature as useEffect, so making the changes should be quite trivial.

  • Related