YouTube Icon

How To Use the New React Context API




How To Use the New React Context API

Rumors are flying! Could Context replace redux? Does it make prop drilling extinct? Even if Context !== world peace, the React team has introduced a fantastic tool to simplify one of the most difficult problems frontend developers deal with daily: state management.

Over the past six months, there has been plenty of hype about the new Context. At the end of this post, you’ll know what it is, whether and when you should use it, and how to implement it in your applications.

What is Context?

Imagine React as a toolbox. In React 15, developers could only use prop drilling to manage their application’s state. (If you don’t know about prop drilling yet, go read this post. I’ll wait).

Developers started reaching for other toolboxes, like redux and MobX to help with more complicated state management. They offered alternative solutions to managing state, but they introduced complexity, increased the bundle size, and required learning another library in addition to React.

Like all abstractions, these tools came burdened with tradeoffs that felt worth it for large applications, but seemed like overkill for small and mid-sized applications.

When Should I Use Context?

I would recommend reaching for Context when you find yourself passing props down through three or more levels in your component tree. You might notice that you have renamed your props, making it challenging to determine the data’s origin. You might consider implementing context if a bunch of your components know about irrelevant data.

Do not hesitate to still use the other tools you have available, like prop drilling and redux. While Context can make it easier to pass props around in certain scenarios, it doesn’t give you access to some of the benefits redux offers, and it’s a more complicated abstraction than prop drilling.

How Do I Use Context?

Now you know what Context is, and when to use it! I’m sure you’re jumping at the bit to discover how to implement it in your applications. I created an example to show how you might replace prop drilling with Context as your application grows.

If you’re into interactivity, I’ve created a Code Sandbox you can explore! I’ll also walk you through my example step-by-step.

Prop Drilling

I’ve built an application that stores a family’s last name in a <Grandmother /> component. The <Child /> component than displays the last name.

We use prop drilling to pass the lastName prop from the <Grandmother /> component, through the <Mother /> component, to the <Child /> component, which displays the last name.

const App = () => <Grandmother />
      
class Grandmother extends React.Component {
  state = {
    lastName: "Sanchez"
  }
 
  render() {
    return <Mother lastName={this.state.lastName} />
  }
}

const Mother = ({ lastName }) => {
  return <Child lastName={lastName} />
}

const Child = ({ lastName }) => {
  return <p>{lastName}</p>
}

Context

We can refactor this example to use Context instead. Using Context means we don’t need to pass the lastName through the <Mother /> component. We circumvent components that don’t need to know the lastName property, and share that state only with components that need to know it.

First, we will need to create our Context.

import React from "react";

const FamilyContext = React.createContext({});

export const FamilyProvider = FamilyContext.Provider;
export const FamilyConsumer = FamilyContext.Consumer;

We use createContext() and pass it an empty object as the default value:

const FamilyContext = React.createContext({});

We then create a Provider and a Consumer component and export them so they are available for consumption by other components in your application.

export const FamilyProvider = FamilyContext.Provider;

export const FamilyConsumer = FamilyContext.Consumer;

Here’s a full example of how we will use the Provider and Consumer:

import React from "react";
import { FamilyProvider, FamilyConsumer } from "./FamilyContext";

export class Grandmother extends React.Component {
  state = {
    lastName: "Sanchez"
  };

  render() {
    return (
      // We wrap all of the components that need access
      // to the lastName property in FamilyProvider.
      <FamilyProvider value={this.state.lastName}>
        <Mother />
      </FamilyProvider>
    );
  }
}

const Mother = () => {
  return <Child />;
};

const Child = () => {
  // We wrap the component that actaully needs access to
  // the lastName property in FamilyConsumer
  return <FamilyConsumer>{context => <p>{context}</p>}</FamilyConsumer>;
};

Now, we have wrapped the <Mother /> component with <FamilyProvider /> because it contains <Child /> which is the component that needs access to the lastName prop.

<FamilyProvider value={this.state.lastName}>
  <Mother />
</FamilyProvider>

Notice that the Provider has a value prop. Pass in whatever state you’d like to share. In our case, we want to share the lastName so we pass in this.state.lastName.

To actually have access to the lastName, we have also wrapped the <p> tag on line 27 in the <FamilyConsumer /> component so that it has access to the context.

Let’s dig a bit deeper into <FamilyConsumer />!

At first, it might look a bit confusing if you aren’t familiar with the render prop pattern, but with a bit of explanation I think you might find that it’s a fairly straightforward implementation. You don’t need to know how to build a render prop to use Context, but it’s a really powerful abstraction!

What’s a Render Prop?

A render prop is a way of writing components in React so that they are reusable, and can take n number of children of any type. Render props appear in a couple of different disguises. Context implements a Function as a Child Pattern, which is just a render prop called children. If you want to learn more about render props, you can read When Not to Use Render Props by Kent C. Dodds or go straight to React’s documentation on the subject.

const Child = () => {
  // Family Consumer uses the
  // Function as a Child pattern
  return <FamilyConsumer>
    // context is the object with lastName
    // on it. It gets passed as an argument
    {context => <p>{context}</p>}
  </FamilyConsumer>;
};

<FamilyConsumer /> uses a render prop to expose the context object to its children (in this case a <p /> tag but it could be anything).

Ultimately, Context is a great tool to add to your React toolbox. Use it when you find prop drilling has become too complex, but your application isn’t large enough to warrant a third-party solution like MobX or redux.



Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

703d9a2733f1fc40f636f9d9cdeff391.png

Best React Libraries That Are Worth Trying In 2023

As per the Stack Overflow survey, React.js was the 2nd most popular web framework after Node...

f6dc0df3856bfe502f41ce4965b0a410.png

How To Deploy Your React Website in 2022!

Different React applications need different arrangement arrangements in view of their case. In th...

4248748df2304b0c9e733eec03bdce2d.png

Higher-Order Components in React

A higher-request component (HOC) is a high level method in React for reusing component rationale....

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team