Skip to content

Instantly share code, notes, and snippets.

@rjz
Created April 11, 2018 02:22
Show Gist options
  • Save rjz/83893f28ea36227c9ec732260cf22375 to your computer and use it in GitHub Desktop.
Save rjz/83893f28ea36227c9ec732260cf22375 to your computer and use it in GitHub Desktop.

React Context API

George Song (Twitter: @zukefresh, Github: @gsong)

  • Need React >= v16.3.0
  • State: Component → Context → Unstated → Redux/MobX/(etc)
  • Two parts: <Provider /> and <Consumer />

How it works

  1. Instantiate a context and receive a Provider and a Consumer
  2. Set context values in the <Provider />
  3. Extract value from <Consumer /> via a render prop (i.e., callback) that receives the value from the context

State can then be updated via callbacks (accessible from the context)

Unlike Redux (one store) context is meant to be as small as possible and specific to some focused part of the app.

Problems Context solves

  • Imagine what we'd have to go through to manage the same state with Redux
  • No prop-drilling, no giant central store
  • Use-cases: context enables...
    • ...local "global" state
    • ..."compound" (i.e., composed) components
    • ..."nested" context (i.e., that depends on other context) -- easy to nest <Provider />s and <Consumer />s and react to changes in the outer context

Further Reading

Thanks, George!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment