Upgrade to Pro — share decks privately, control downloads, hide ads and more …

useHooks

Avatar for Kartik Lad Kartik Lad
February 20, 2019

 useHooks

An introduction to React Hooks with examples and how it could help simplify existing React components from issues like Wrapper Hell and distributed/repeating logic.

Avatar for Kartik Lad

Kartik Lad

February 20, 2019
Tweet

Other Decks in Programming

Transcript

  1. Distributed logic Unrelated code is grouped together while related code

    is split across lifecycle methods Issues with React components Where is the State? Function components can’t use State ¯\_(ツ)_/¯ this.function.bind(this) Having to bind this to functions to allow access react internals
  2. THE GOOD STUFF • Don’t have to worry about `this`

    or `class` • Typing is easier • Simplify large components by splitting up related pieces into smaller functions • Reuse stateful logic • Use React features without classes • Backward compatible and works side-by-side with your existing codebase.
  3. Only call hooks from React Call hooks from React function

    components or other custom hooks Use the Eslint plugin Do yourself a favour and use eslint-plugin-react-hooks.. This way you wont forget any of the above rules Only call hooks at top level Don’t call Hooks inside loops, conditions, or nested functions Rules of Hooks
  4. Only call hooks from React Call hooks from React function

    components or other custom hooks Use the Eslint plugin Do yourself a favour and use eslint-plugin-react-hooks. This way you wont forget any of the above rules Only call hooks at top level Don’t call Hooks inside loops, conditions, or nested functions Rules of Hooks
  5. Only call hooks from React Call hooks from React function

    components or other custom hooks Use the Eslint plugin Do yourself a favour and use eslint-plugin-react-hooks. This way you wont forget any of the above rules Only call hooks at top level Don’t call Hooks inside loops, conditions, or nested functions Rules of Hooks
  6. useState is a hook that lets you attach React state

    to a function component. useState
  7. Use this hook to tell React that your component needs

    to do something after every render. useEffect
  8. useEffect(() => { // add effect return () => {

    // remove effect } }, [/* when to clean up */]) SSR friendly!

  9. Similar to useEffect, except it is synchronous and blocks rendering

    on the browser useLayoutEffect Not SSR friendly
 ⚠
  10. const isValid = useRef(‘some value’); // You can pass anything

    as default value // Access the value isValid.current = true; If (isValid.current) { … } // ⚠ This is always true If (isValid) { … }