Let's learn about Context API
What is Context API ?
It's a React way to enable and exchange of data between children without using prop-drilling. This is Use to avoid prop drilling. it is also lighter approach to state management using Redux.
It added in react after version 16.3
How to use Context API
So there are three parts of context API
- Create a Context
- Provider method will provide value to all children components.
- Consumer will consume value which is provided by provider
In this Blog we will learn to use context API separate context.js file
Create a Context
To create context, just import createContext() method from React in context.js
import React from "react";
export const AppContext = React.createContext()
Provide method will provide value to all children Component
const ParentContext = (props) => {
const [data, setData] = useState("")
const updateDataHandler = (value) => {
setData(vlaue)
}
return (
<AppContext.Provider value={{data,updateDataHandler}}>
{props.children}
</AppContext.Provider>
)
}
export default ParentContext;
This can be done in the same context.js file. Here we are providing data & updateDataHandler function to all children in AppContext so besicly we can use data at any level of our component Tree without performing prop drilling.
Now just import parrentContext component in user another component tree where you want to use the data here I am using my data in app.js where I want to use data in my whole app
import ParentContext from "./context.js";
import Child from './Child.js'
function App() {
return(
<ParentContext>
<Child />
</ParentContext>
);
}
export default App;
see in child component we are not passing any of this as props
Consumer will consume value which is provided by provider
Child is our consumer where we want to consume our data & change data using updateDataHandler() function
import { useContext } from "react";
impoer { AppContext } from "./context.js"
const Child = () => {
// consuming data using hook
const { data, updateDataHandler } = useContext(AppContext)
// consuming data using hook
return <>
<h2> {data} </h2>
<button onClick={ () => updateDataHandler("newData") }> Click me to change Data </button>
</>
}
export default Child;
Here we are consuming data & updateDataHandler using hook called useContext() where we pass our context, and we get that data which we want to use in this component and when click on button, data is getting update and reflecting in component
So this is Context API using hooks, I hope you understand. Please share with your friend and keep learning