We're planting a tree for every job application! Click here to learn more

Building with React Context Provider Pattern

King Somto

4 Aug 2021

3 min read

Building with React Context Provider Pattern
  • JavaScript

Introduction

In this article, we will be going through the use of the React Context Providers in building React applications. React uses the Context provider to share data across multiple children components in our React App without the need to pass data or functions across multiple components, however, it comes in handy when building applications with lots of dependencies and moving parts.

What is React Context API

According to the gospel or the React Docs in the book of Context, it defines the context as “ a way of passing data through the component tree without having to pass props down manually at every level”.

React applications let parent components pass data long to children components but issues arise when that data is meant to be used by children components multiple layers deep but not by immediate children of that parent component. Let's look at the diagram below.

Screen Shot 2021-06-27 at 12.02.36 PM.png

Component A is clearly the main parent component with immediate children components B, C, D, these components can receive params from component A and pass that data to the children components, but what about a scenario where Component F needs data from component A and that data is not needed in component B then passing that data to component B becomes redundant, Contex providers provide a cool way of making data readily available to every single child component in the React Application.

What is it used for?

Context API provides a way of sharing data with multiple components throughout our React Application this enables us to be creative in how we manage our application state in things like

  • Authentication: Knowing when a user is logged in or has an active user session or just hold user data

  • Notifications: I normally use a Notification provider to expose a notification alert function to components in my application.

  • Theming: A cool use of this is controlling night mode in applications look at a cool implementation of that here

  • Loading of data at start of the application

React Context Provider example

This is a simple example of a React context Provider

export const RandomContext = createContext({ user: null });
 
class RandomProvider extends Component {
 state = {
   user: "Somto"
 };
 
 render() {
   return (
     <RandomContext.Provider value={this.state}>
       {this.props.children}
     </RandomContext.Provider>
   );
 }
}
 
const ComponentTest = () => {
 const { user } = useContext(RandomContext);
 return (
   <div>
     <p>{user}</p>
   </div>
 );
};
 
export default () => {
 return (
   <div>
     <RandomProvider>
       <ComponentTest />
     </RandomProvider>
   </div>
 );
};

The user Variable would contain the value Somto.

Adding useState to React Context

Combining useState with react context helps to add extra functionality to our React app, now components can interact and change the data present in the Context Provider and these changes can be seen in the entire app.

Building an example application

For our example application, we are going to build a Simple React counter where we would be able to increase and decrease the value of a number stored in the Context, this would be done by different components by accessing the usestate set Function to change the value.

Step 1. Build and export the context provider

Let's look at the example below of our new Context Provider.

import React, { Component, createContext, useContext } from "react";
const CountContext = createContext({ count: 0, setCount: () => {} });
 
const CountProvider = ({ children }) => {
 const [count, setCount] = React.useState(0);
 
 return (
   <CountContext.Provider value={{ count, setCount }}>
     <p>{count}</p>
     {children}
   </CountContext.Provider>
 );
};
 
export const useCountContext = () => useContext(CountContext);
 
export default CountProvider;

Let's break this down.

 const CountContext = createContext({ count: 0, setCount: () => {} });\

This part of the code is used to create a context to contain the count variable and the setCount function that would be available throughout the children component.

 const [count, setCount] = React.useState(0);

This initiates our useState variables.

 
 return (
   <CountContext.Provider value={{ count, setCount }}>
     <p>{count}</p>
     {children}
   </CountContext.Provider>
 );

Here we return our ContextProvider, pass in the values variable and pass the children props variable as its own children.

export const useCountContext = () => useContext(CountContext);
 
export default CountProvider;

Export both the UserCountContext and the Context Provider Itself.

Step 2. Using our provider and calling the setCount.

import "./styles.css";
import React, { useContext } from "react";
import ReactDOM from "react-dom";
import CountProvider, { useCountContext } from "./provider";
 
const Component = () => {
 const { count, setCount } = useCountContext();
 
 return (
   <div>
     <button
       onClick={(e) => {
         setCount(count + 1);
       }}
     >
       Add
     </button>
     <button
       onClick={(e) => {
         setCount(count - 1);
       }}
     >
       Subtract
     </button>
   </div>
 );
};
 
ReactDOM.render(
 <CountProvider>
   <Component></Component>
 </CountProvider>,
 document.getElementById("app")
);

Conclusion

React context provider offers a way of maintaining state globally across our application, we can read and edit that state in any component we choose to, without passing dependencies in through the tree hierarchy.

A working example of this code is available here

Did you like this article?

King Somto

I am a DevOps Engineer

See other articles by King

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
email iconhello@works-hub.comUK flag

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

US flag

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2023 WorksHub

Privacy PolicyDeveloped by WorksHub