Skip to content

Instantly share code, notes, and snippets.

@mlimberg
Last active December 13, 2018 17:55
Show Gist options
  • Save mlimberg/10ddded589adc1c7101453f233414994 to your computer and use it in GitHub Desktop.
Save mlimberg/10ddded589adc1c7101453f233414994 to your computer and use it in GitHub Desktop.

Hooks:

What is it?

Hooks are functions that let you “hook into” React state and lifecycle features from function components.

  • useState

    • deconstruct/define? value name and update function
    • const [name, updateName] = useState('Greg')
    • each time you use a useState hook, it isolates its own state
      • extracting an update state call into a reusable generic function works to define separate states
  • useContext

    • deconstruct/use values from React context
    • const [theme, updateTheme] = useContext(ThemeContext)
  • useEffect

    • essentially lifecycle methods replacement
    • ComponentDidUpdate often needed to ensure proper re-rendering with updates...forgetting to handle componentDidUpdate properly is a common source of bugs in React applications.
    • You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect (instead of === comparison for everything)
  • useRef

  • useReducer

    • Whaaaaat?!

Rules:

  • You cannot use hooks inside of a conditional, have to be declared at top level

Custom Hooks:***

  • Using react hooks to extract pieces of a functional component
  • Always start with "use" to mirror react hooks syntax

Notes:

  • Hooks don’t replace your knowledge of React concepts. Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them
  • Shared state between components is hard. With hooks you can create custom hooks and share state amongst multiple components easier than HOC's or render props
  • Classes present issues for today’s tools. For example, classes don’t minify very well, and they make hot reloading flaky and unreliable.
  • Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment