How To Work with Context API in React and React Hooks
Table of Contents
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 #
An understanding of React is required. To learn more about React, check out the How To Code in React series.
A general knowledge of React Hooks is suggested but not required. To learn more about React Hooks, check out the tutorial How To Apply React Hooks in Your React Project.
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.
useContext()
Method>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.