2. Background
☞ Introduced in React version 16.8.
☞ Hooks enable adding state and side effects to Functional
Components.
☞ Essentially replace the need for Class components.
In the eyes of the React Team:
☞ What a true component should be: "A function with state".
☞ The mindset: Call a function for rendering.
3. Background
Classes Components are not “real classes”:
😐 We shouldn't inherit a class component.
😐 We cannot do dynamic binding (Polymorphism).
😐 We do not use the “new” keyword.
😐 We do not move around instances like we do with objects.
😐 Members go into ”State”?!
😐 What are props? (params to a function? a constructor?)
From an interview with Dan Abramov
4. Motivation
😺 Functionality Reuse:
- Extract repeating code to a custom hook (including state and side effects).
- Simpler then HOC (Higher Order Components) and "Render Props".
😺 Smaller code, co-located:
- E.g. useEffect() may replace code that was previously spread over several
lifecycle methods.
😺 Functional components are less verbose.
7. useState
Gotchas / Tips :
✍ Different from setState() of a class component: Does not merge!
✍ If we pass to it a func -> it will run only on the first time
❌ useState(calc(props)) // calc() will run every time
✅ useState(() => calc(props))
✍ Prefer using the functional way
(you’ll be less likely to encounter “Stale State” ).
10. useEffect
Purpose: Handle side effects (mostly).
How depArr affects behavior:
Nothing → Run after each render / Cleanup before every next render
[] → Run only after mount / Cleanup before unmount
[deps...] → Run only after dependencies change / Cleanup before next render
Demo..
Or (named):
11. useEffect:
Gotchas / Tips :
✍ beware of one-liners – They might return a value:
❌
✍ Make sure you define a func for cleanup (instead of calling it):
❌
⚠️ Do not automatically ignore the ”exhaustive-deps” eslint rule as
it may indicate a bug in your code!
12. useEffect:
Gotchas / Tips:
✍ useEffect should only have “Stable References” as dependencies:
A stable ref is a reference which is constant. Examples:
✅ Consts we define outside the component (props too).
✅ The func returned from useState / useCallback().
✅ Variables we define with useRef().
❌ A const defined in a component → it is redefined on each run.
13. useLayoutEffect:
In some (rare) cases you'll want to do something synchronously
after a render. E.g., read / right to the DOM.
Then use useLayoutEffect() instead of useLayoutEffect().
14. useCallback
Purpose: Create a memoized function.
Useful for passing a funcion as dependency to:
♤ useEffect // otherwise we'll see the 'exhaustive-deps' lint error.
♤ a child component // avoid re-rendring the child on every parent render.
Demo..
15. useMemo
Purpose: Create a memoized value.
♤ Use as a performance enhancement:
In this case the app should work logically the same without it.
https://medium.com/javascript-in-plain-english/react-usememo-and-when-you-should-use-it-e69a106bbb02
♤ Can be used to replace useState + useEffect when useEffect does pure
calculations (i.e. no side effects).
https://stackoverflow.com/questions/56028913/usememo-vs-useeffect-usestate
16. useRef
Purpose: Creates a ”Stable Ref” / ref to the DOM.
♤ Returns an object with the attribute 'current’.
♤ Mutable.
♤ Mutations do not cause a re-render.
Demo..
17. useRef
Usages examples:
♤ Refer to a DOM element (like createRef() in classes):
=> Detect clicks outside the element, find its size etc.
♤ Store a mutable value across the lifespan of the component
(like placing a value on “this” in a class).
=> Access a var from different funcs, keep previous state etc.
⚠️ Modify refs in event handlers and effects, not the
“render” (=the body of the component).
18. Hooks Rules!
📜 Do not place hooks behind conditions!
Make sure all are called every time the component “runs”.
Best practice: Place at the top of the component.
📜 Call hooks only from functional components or custom hooks!
* Enforced using the eslint-plugin-react-hooks rules.
19. Custom Hooks
🚀 Enable logic reusability between (and within) components.
🚀 Added bonus: Hooks created by the community:
→ Gists.
→ Npm packages.
* Same hooks rules apply.
* The name should start with “use” (otherwise we lose the linter’s help).
Demo..
20. Links
📃 The official Docs: https://reactjs.org/docs/hooks-intro.html
📃 Useful hooks (for copy+paste): https://github.com/gragland/usehooks
📃 Useful hooks (as npm packages): https://github.com/gragland/usehooks
📃 Huge collection of hooks related links:
https://github.com/rehooks/awesome-react-hooks