We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies.

We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies. Less

We use cookies and other tracking technologies... More

Login or register
to publish this job!

Login or register
to save this job!

Login or register
to save interesting jobs!

Login or register
to get access to all your job applications!

Login or register to start contributing with an article!

Login or register
to see more jobs from this company!

Login or register
to boost this post!

Show some love to the author of this blog by giving their post some rocket fuel ๐Ÿš€.

Login or register to search for your ideal job!

Login or register to start working on this issue!

Login or register
to save articles!

Login to see the application

Engineers who find a new job through JavaScript Works average a 15% increase in salary ๐Ÿš€

You will be redirected back to this page right after signin

Blog hero image

Building with React Context Provider Pattern

King Somto 4 August, 2021 | 3 min read

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.

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

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

Author's avatar
King Somto
I really dont know much but am willing to try and learn

Related Issues

open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Started
  • 0
  • 2
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Started
  • 0
  • 2
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Open
  • 0
  • 0
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Started
  • 0
  • 1
  • Intermediate
  • HTML

Get hired!

Sign up now and apply for roles at companies that interest you.

Engineers who find a new job through JavaScript Works average a 15% increase in salary.

Start with GitHubStart with Stack OverflowStart with Email