This code example wants to do two thing:
- Show you when to use the
useLayoutEffecthook. - Understand the
useStatehook better by analyzing an a-typical use of it. - Understand the (
useEffect/useLayoutEffecthook) dependency array better with this tricky example
-
Issue 1: Observe flickering because of
useEffectin this CodeSandBox -
Solution with
useLayoutEffect: This CodeSandBox -
useLayoutEffectin React Native Example: TriggerLayoutEffecton mount of component won't work withuseEffectbecause it'd happen too late.
- Issue 2:
react-hooks/exhaustive-depsissue: 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.
177in my case). Setting it to177again won't cause a re-render.
useLayoutEffecthas 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.
renderis 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
useStatehook instead of a value. Read this article for more information about it.
