Tutorial

How To Work with Context API in React and React Hooks

Updated on November 11, 2020
Default avatar

By Stephen Hartfield

How To Work with Context API in React and React Hooks

Introduction

In this article, you will examine how to implement Context API and the React Hook useContext() in your React project. The Context API is a React structure that allows you to share specific data from all levels of your application and aids in solving prop-drilling.

React Hooks are functions that serve as a modular replacement for state and lifecycle methods written in functional components. The useContext() method is an alternative to prop-drilling through the component tree and creates an internal global state to pass data.

Prerequisites

Examining the Context API

To examine the Context API, let’s approach how to access context in a React application. React offers the createContext() method to assist in passing data as a prop.

In your ColorContext.js file, set a colors object and pass a property as an argument to the createContext() method:

ColorContext.js
const colors = {
  blue: "#03619c",
  yellow: "#8c8f03",
  red: "#9c0312"
};

export const ColorContext = React.createContext(colors.blue);

This will allow the .createContext() method to subscribe the property colors.blue as a prop from one component to another.

Next, you can apply the .Provider component to your context in another file. The .Provider component enables the data in your context throughout your entire application. In your index.js file, import your ColorContext function and append to the .Provider component in your return statement:

[label index.js] 
import React from 'react';
import { ColorContext } from "./ColorContext";

function App() {
  return (
    <ColorContext.Provider value={colors}>
      <Home />
    </ColorContext.Provider>
  );
}

This wraps the context of your ColorContext function to color your application. While your ColorContext function exists in the component tree, the .Provider component will facilitate its functionality throughout. Here, the Home component will absorb the data within your ColorContext function. Child components of Home will also obtain the data from ColorContext.

You can also apply the .Consumer component to subscribe to a context’s changes. This is available in both class and functional components. The .Consumer component is only accessible within a return statement. In your index.js file, set a .Consumer component to your ColorContext function in your return statement:

[index.js]
return (
  <ColorContext.Consumer>
    {colors => <div style={colors.blue}>Hello World</div>}
  </ColorContext.Consumer>
);

Whenever the context changes, the .Consumer component will update and adjust your application based on the modification.

You can give your component a context type: MyComponent.contextType = ColorContext; then, you can access the context in your component: let context = this.context; and that allows you to access your context outside of the JSX. Or instead, you could put in static contextType = ColorContext;. This works pretty good for class-based components since it simplifies how to bring your context into your component. But, it will not work in a functional component.

You may also declare a context with the .contextType property on a class component and assigns its value the ColorContext function. You can also assign your ColorContext function to the static contextType Context API. These methods apply only within class components. Let’s review how to call on context within a functional component.

Handling the useContext() Method

The useContext() method accepts a context within a functional component, and works with a .Provider and .Consumer component in one call. In your index.js file, import the useContext() method and the ColorContext function, and declare a functional component:

index.js
import React, { useContext } from "react";
import ColorContext from './ColorContext';

const MyComponent = () => {
  const colors = useContext(ColorContext);

  return <div style={{ backgroundColor: colors.blue }}>Hello World</div>;
};

The functional component MyComponent sets the value within your ColorContext as an argument to the useContext() method. Your return statement applies the background color in your application. When a change triggers, the useContext() method will subscribe update with the latest context value. Compared to the Context API, the useContext() method allows you to share and pass data throughout your application in fewer lines of code.

Conclusion

The Context API in React provides you with built-in functions and components to avoid prop-drilling in your component tree. The React Hook useContext() applies the same functionality in a streamlined, functional component body in one call.

Check out the React topic page for additional projects and resources.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Stephen Hartfield

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel