UseContext— A Side Note to the Official Doc

The following can be read as a side reference to the official React Doc:

Image for post
Image for post


In case you haven’t heard of React’s Context API, it’s a way to pass data deeply throughout your app without having to manually pass props down through multiple levels, which I’d assume we have all complained about when passing props from grandparents to grandchildren …

The typical way to use the Context API before useContext looks like this:

import React from "react";
import ReactDOM from "react-dom";
// step 1. Create a Context
const NumberContext = React.createContext();
// It returns an object with 2 values:
// { Provider, Consumer }
function App() {
// step 2. Provide a value/values
// Use the Provider to make a value available to all
// children and grandchildren
return (
<NumberContext.Provider value={42}>
<Display />
function Display() {
// step 3. Consume the value from a child
// Use the Consumer to grab the value from context
return (
{value => <div>The answer is {value}.</div>}
ReactDOM.render(<App />, document.querySelector("#root"))

Let’s rewrite the Display using the new useContext hook and see what it looks like:

// import useContext (or we could write React.useContext)
import React, { useContext } from 'react';
// ...function Display() {
const value = useContext(NumberContext);
return <div>The answer is {value}.</div>;

That’s all there is to it. So to break down:

  • Create context use syntax
const YourContext = React.createContext()
  • Create a value set to be passed in (can be object as well)
<YourContext.Provider value={value}></YourContext.Provider>
  • Wrap it around the components that need to access the value (can be root App or any individual component)
<YourContext.Provider value={value}>{children}</YourContext.Provider>
  • Access the value in children
const value = useContext(YourContext)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store