What is Context API:
The context API in React is used to share specific forms of data across all levels of the application which you can't share easily with props. why Context API? The main aim of context API is to solve the problem of prop drilling now what is props drilling? code in react is always divided into multipe components so using prop drilling you can manually transfer the data from one component to other.Transferring the data using props on a large project is a hassle so to overcome this the concept of Redux and Context Api come into picture.
How to use Context API:
1:For using Context we need to import it first like we import other dependencies in react.
code snippet:
import React, { createContext } from "react";
const UserContext = createContext();
2:provide a value for a Context in the hierarchy. here we are using React Hooks.
code snippet:
const UserProvider = ({ children }) => {
const [name, setName] = useState("John Doe");
const [age, setAge] = useState(1);
const happyBirthday = () => setAge(age + 1);
return (
<UserContext.Provider value={{ name, age, happyBirthday }}>
{children}
</UserContext.Provider>
);
};
3:Accessing the current Context value in the hierarchy.
Code snippet:
const withUser = (Child) => (props) => (
<UserContext.Consumer>
{(context) => <Child {...props} {...context} />}
{/* Another option is: {context => <Child {...props} context={context}/>}*/}
</UserContext.Consumer>
);
4:Finally export them:
code snippet:
export { UserProvider, withUser };
What is a React Context Provider?
A React Context API has two concepts: a Provider and a Consumer. The Provider is a higher order Component in the Tree, and provides data and functions for lower portions of the Component Tree to access.
What is a React Context Consumer?
The Consumer is the inverse part of the React Context API, the part which accesses or consumes the data and functions provided by the Provider.