React Context API
Here in this blog, we will learn what is React Context API.
Context:
- Context in React is a (kind of) new feature built-in API introduced in React 16.3.
- It makes it possible to pass data from the parent component to the children component nested deep down the component tree directly, instead of passing it through a chain of props.
Actors in Context:
The two main actors in context are – the Provider provides the object in context and the Consumer consumes these data from the context in the sub-tree.
Consumers :
A React component that subscribes to the context changes, Using this component lets you subscribe to the context within the function component, Requires the function as a child, the function receives the current context value, and returns a React node.
Producers:
Every Context object comes with a Provider React component that allows consuming components to subscribe to the context changes. The Provider component accepts the value prop to be passed to consuming components that are descendants of this Provider. One Provider is connected to many consumers.
How to use Context API?
- Make a contexts folder in your app’s root. (not required. just a convention)
- Create a file named <your context name>Context.js, e.g. userContext.js
- Create the context using the createContext method.
- Take your created context and wrap it to the context provider around your component tree.
- Put any value on your context provider using value prop.
- Read that value within any component using context consumer.
Example :
let’s pass down our own name using Context API and read in nested component: User.
import React from 'react'; import React, { createContext } from "react"; export const UserContext = createContext(); export default function App() { return ( <UserContext.Provider value="Reed"> <User /> </UserContext.Provider> ) } function User() { return ( <UserContext.Consumer> {value => <h1>{value}</h1>} {/* prints: Reed */} </UserContext.Consumer> ) }
The benefit of Context API:
- It is scalable. Context API can used for any web application.
- It is less complex than Redux. The workflow is simpler than Redux.
- It has lower implementation costs.
- No need to pass data to the children component at each level.
- It is easy to maintain and it is reusable.