How to use Context API In ReactJS
In this approach we start with creating context object and using ContextObject.Provider to provide the prop values from parent component to child component. ContextObject.Consumer is used to consume the prop values inside child component provided from parent component.
- createContext() – This is used for creating the Context object
- ContextProvider – This method will help to provide the context values
- ContextConsumer – This method is used to consume the context values
Syntax:
const ContextObject = React.createContext();
const ComponentName = () => {
<ContextObject.Consumer>
{
value => <div>{value}</div>
}
</ContextObject.Consumer>
}
Example: Below is an example of accessing props using context API.
// ContextObject.js
import React from 'react';
const ContextObject = React.createContext();
export default ContextObject;
// Parent.js
import React from 'react';
import Child from './Child';
import ContextObject from './ContextObject';
const Parent = () => {
return (
<ContextObject.Provider value="Geeks For Geeks">
<Child />
</ContextObject.Provider>
);
};
export default Parent;
// Child.js
import React from 'react';
import ContextObject from './ContextObject';
const Child = () => {
return (
<ContextObject.Consumer>
{
value => <div>{value}</div>
}
</ContextObject.Consumer>
);
};
export default Child;
Output:
Different ways to access props inside a Component in React
The props keyword is the shorthand for properties. It is one of the most important features of React which helps in effective communication between various React components. It is a read-only attribute for passing data from the parent component to the child component. There are various ways to access props inside a component.
We will discuss the ways to access props inside a component.
Table of Content
- Functional Components:
- Class Components:
- Destructuring
- Using Context API:
- Using useContext() hook: