This code example wants to do two thing:
- Show you when to use the
useLayoutEffect
hook. - Understand the
useState
hook better by analyzing an a-typical use of it. - Understand the (
useEffect
/useLayoutEffect
hook) dependency array better with this tricky example
-
Issue 1: Observe flickering because of
useEffect
in this CodeSandBox -
Solution with
useLayoutEffect
: This CodeSandBox -
useLayoutEffect
in React Native Example: TriggerLayoutEffect
on mount of component won't work withuseEffect
because it'd happen too late.
- Issue 2:
react-hooks/exhaustive-deps
issue: missing deps and then "extract it to a separate variable so it can be statically checked" - i.e. make the code simple enough so that eslint can statically analyze it (i.e. without running the code).
- Bonus question: Passing which value to
setWidth();
could stop this re-rendering invocation? - Reply: Set it to the initial width of the rectangle (e.g.
177
in my case). Setting it to177
again won't cause a re-render.
useLayoutEffect
has same signature asuseEffect
- Runs synchronously after render but before DOM manipulation and paint to screen.
- This article summarizes its use nicely.
If your component is flickering when state is updated – as in, it renders in a partially-ready state first and then immediately re-renders in its final state – that’s a good clue that it’s time to swap in useLayoutEffect.
- Heuristic when to use it: If your component is flickering when state is updated.
render
is a React render. It doesn't refer to DOM updates or to paints to the screen.- lazy initializers is e.g. a function as initial state in a
useState
hook instead of a value. Read this article for more information about it.