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.
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
```import React, { Component, createContext, useContext } from "react";
export const RandomContext = createContext({ user: null });
class RandomProvider extends Component {
state = {
user: "Somto"
};
render() {
return (
{this.props.children}
);
}
}
const ComponentTest = () => {
const { user } = useContext(RandomContext);
return (
{user}
);
};
export default () => {
return (
);
};
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.
```js
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
Originally written by King Somto for JavaScript Works
Top comments (0)