Context and Hooks - mattoattacko/class GitHub Wiki

Context

  • Context gives us a way to pass data through the component tree w/o having to pass props down manually at every level.
  • In React apps, data is usually passed from the top-down (parent to child) via props. This can be annoying for certain types of props that are required by many components w/in an application.
  • Context gives us a way to share values between components w/o having to explicitly pass a prop through every level of the tree.

Using Context

  • Context lets us share data that can be considered global in scope for a tree of React components (eg: current authenticated user, theme, etc).
  • Allows us to avoid passing props through intermediate elements.
  • Useful when some data needs to be accessible by many components at different nesting levels.
  • Since context uses reference identity to determine when to re-render, we need to be careful not to trigger unintentional renders in consumers when a provider's parent re-renders.

Hooks

  • Hooks are a feature that allows us to use state and other React features w/o writing a class.
  • Hooks are functions that let us "hook into" React state and lifecycle features from function components, and allow us to use React w/o classes.
  • Hooks are JS functions and are backwards-compatible.
  • We can use the useState Hook inside a function component to add some local state to it. React will preserve this state between re-renders. We can use the State Hook more than once in a single component.
  • Effect Hooks can affect other components and can't be done during rendering (eg: data fetching, subs, changing the DOM from React components).
  • useEffect gives us the ability to perform "side effects" from a from a function component.
  • Calling useEffect tells React to run our effect function after flushing changes to the DOM.
  • Effects are declared inside the component so they have access to its props and state.
  • Hooks let us organize side effects in a component by what pieces are related, instead of forcing a split based on lifecycle methods.

Using Hooks

  • We should only call Hooks at the top level.
  • We should only call Hooks from React function components. Don't call Hooks from regular JS functions.
  • Building our own Hooks allows us to reuse some stateful logic between components.