- Views: 1
- Report Article
- Articles
- Technology & Science
- Communication
An in-depth guide on Context API in ReactJS
Posted: Nov 14, 2022
Component state are crucial in React project development. Employing state is easy when we have to use data only in one component. But it gets tricky when we require to use data with multiple components. In this blog, we will see how to use state data globally using context API.
It is critical to understand the React fundamentals: Props and State, because we know react works on state-based functionality and to use state data globally from component to component, we have to use props.
Props passes the state from parent to child component. There are two problems with props passing.
- Prop Drilling
- Unnecessary codes
Let's understand Both problems.
What is Prop Drilling?
Prop drilling refers to the process of sending props from a parent component to a child component. When we pass props from the parent component to the child component then it will create a hierarchy between components.
To understand it better, let us create a small project with a prop drilling method:
There are 4 components named A, B, C, and D.
We are passing state as a prop from App Component to A, A to B, B to C, and C to D.
Folder Structure:
Figure 1. Folder Structure
App.js
import { useState } from "react";
import A from "./Parent/A/A";
function App() {
const [data,setData] =useState("Context Api")
return (
A data={data} /
)
}
export default App;
A.js
import B from "../B/B";
const A = (props) => {
return (
)
}
export default A;
B.js
import C from "../C/C";
const B = (props) => {
return (
)
}
export default B;
C.js
import D from "../D/D";
const C = (props) => {
return (
)
}
export default C;
D.js
const D = (props) => {
return (
Props : {props.data}h1>
)
}
export default D;
Output:
Figure 2. Output
In the above-provided codes you can see that there is creating one type of hierarchy between all the five components like below:
Figure 3. Prop Drilling
Now, the question arises what if I don’t want to pass the state in props and want to pass the state as a global state. Repetitive code of prop dealing becomes an issue
Question: So, what’s the best way to fix this new issue?
Answer: Pass the state as a global state.
If we pass the state as global, we can access it in any component.
We can Pass the State as a global using two ways.
- Context API
- Redux
In this tutorial, we use context API. Let us learn context API step by step.
What is Context API?
Data is passed from parent to child via props in a normal react application.
But wait, one question arises in the mind ‘’what if we want to pass state in all of the components."
" Is it okay to transfer props from the parent side to the child part?" This creates a prop drilling.
Context provides a way to share values like these between components without passing a prop through every component.
Why to use Context API?
Context is implemented to share data that can be considered as a global state for React components.
We can pass the value to any component.
Practical of Context API
For using context API we have to understand two hooks createContext react app and useContext.
1. createContext:
createContext creates a Context object. When React renders a component then first it will find which providers are used in this component. After that, it will read the current value from the provider.
To achieve this, we will first create a context object. When the object is created using "createContext", then we have to use the context object. After Making the context object we have to provide it on the top-level component.
2. useContext:
useContext hook provides all the data globally. We can access these data in any of the components. Here, we don’t need to pass the props on each level.
There are four steps to Implement React context:
- Create context using the createContext method.
CartContext.js
import {createContext} from 'react'
export const CartContext = createContext();
Here we have created one ContextProvider object which will hold the state data.
Using the createContext hook we easily get the state value in the component.
2. Put any value you like on your context provider using the value prop.
StateProvider.js
import { CartContext } from "./CartContext";
const initialState ={
Name:"Akash",
Age:23,
Gender:'Male',
Country:"India"
}
const StateProvider=({children})=>{
return (
{children}
CartContext.Provider>
)
}
export default StateProvider;
Here we have created a provider named "stateProvider". We have defined one initialState, we will pass this initialState in the value prop. If we want to pass any function then we have to pass that in the value object.
- Take your created context and wrap the context provider around your component tree.
Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import StateProvider from './Service/StateProvide';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
StateProvider>
React.StrictMode>
);
Now, in this step, we have to pass our state data to the whole application.
For passing the data we have to create a wrapper in the App Component.
So we had wrapped our StateProvider to the app.
- Read that value within any component by using the useContext hook.
D.js
import { useContext } from "react";
import { CartContext } from "../../Service/CartContext";
const D = () => {
const state = useContext(CartContext);
return (
Using Context APIh1>
Name : {state.initialState.Name}h3>
Age : {state.initialState.Age}h3>
Country : {state.initialState.Country}h3>
Gender : {state.initialState.Gender}h3>
)
}
export default D;
In this step, we have to take our state data in the component. First, create one object Of useContext and pass the CartContext in that object. Using this CartContext We can access our global state.
Conclusion
Component state is critical in the creation of React projects. When we just need to use data in one component, using state is simple. However, it becomes difficult when we need to use data with several components. In this blog, we have looked in detail how to use state data globally with the context API.
About the Author
Digital Marketing Manager, iFour Technolab Pvt. Ltd. Technocraft and entrepreneur of a reputed.Net development company with years of experience in building large-scale enterprise web, cloud and mobile applications using latest technologies.
Rate this Article
Leave a Comment