Table of contents
No headings in the article.
In React, the Context API allows you to create a global state that can be accessed by any component in your application, without passing props through all the intermediate components. It provides a way to share data between components without the need for explicit prop drilling.
Here's an example of how to use the Context API in React:
- Create a new context using the
createContext
function from the React library:
jsxCopy code// AppContext.js
import React from 'react';
const AppContext = React.createContext();
export default AppContext;
- Set up a provider component that wraps the part of your application where you want to make the context available:
import React from 'react';
import AppContext from './AppContext';
function App() {
const sharedData = {
// Define your shared data here
message: 'Hello from the context!',
count: 42,
};
return (
<AppContext.Provider value={sharedData}>
{/* Your app components */}
</AppContext.Provider>
);
}
export default App;
In this example, the sharedData
object contains the data that you want to share across your components. It can be any JavaScript value, such as objects, arrays, or primitives.
- Access the context data in any component that needs it using the
useContext
hook:
import React, { useContext } from 'react';
import AppContext from './AppContext';
function ExampleComponent() {
const sharedData = useContext(AppContext);
return (
<div>
<p>{sharedData.message}</p>
<p>{sharedData.count}</p>
</div>
);
}
export default ExampleComponent;
In this component,
useContext
is used to access the shared data from the context. By callinguseContext(AppContext)
, thesharedData
object from theAppContext.Provider
in the parent component (App.js
) will be assigned to thesharedData
variable.Note: Make sure the components that access the context are descendants of the
AppContext.Provider
component.By using the Context API, you can share data and state between different components without passing
The components that upgrade the global storage should be placed as a children element of the Context.Provider
If placed outside they will not able to access the context global variable
Difference between global variables and useContext is that react monitors the useContext and hence is able to use the reconcilation processs, but on the other hand global variables are not monitored