The Context API in React.js provides a way to share values like themes, authentication status, or other global settings between components without having to pass the data through each level of the component tree explicitly. It helps avoid "prop drilling" by allowing you to create a centralized place to store and manage state.
Here's a basic overview:
-
Creating a Context:
Use the
createContext
function to create a context. This function returns two components - aProvider
and aConsumer
. TheProvider
is used to wrap the parent component and provide the value, while theConsumer
is used in child components to access that value.
// MyContext.js
import { createContext } from 'react';
const MyContext = createContext();
export default MyContext;
-
Using Context Provider:
Wrap the part of your component tree that needs access to the context with the
Provider
. Pass the value you want to share as a prop to theProvider
.
// App.js
import React from 'react';
import MyContext from './MyContext';
const App = () => {
const sharedValue = 'Hello from Context';
return (
<MyContext.Provider value={sharedValue}>
<ChildComponent />
</MyContext.Provider>
);
};
-
Accessing Context in Components:
Use the
useContext
hook or theConsumer
component to access the context value in child components.
// ChildComponent.js
import React, { useContext } from 'react';
import MyContext from './MyContext';
const ChildComponent = () => {
const contextValue = useContext(MyContext);
return <div>{contextValue}</div>;
};
Alternatively, you can use the Consumer
component:
// ChildComponent.js
import React from 'react';
import MyContext from './MyContext';
const ChildComponent = () => {
return (
<MyContext.Consumer>
{(contextValue) => <div>{contextValue}</div>}
</MyContext.Consumer>
);
};
-
Default Values:
You can provide a default value when creating the context. This default value is used when a component does not have a matching
Provider
in its ancestry.
const MyContext = createContext('default value');
In this case, if there's no matching MyContext.Provider
up the component tree, the default value 'default value'
will be used.
The Context API is especially useful for managing global state that needs to be shared across many components. However, it's important to use it judiciously, as overusing context for every piece of state in your application can make the code harder to understand and maintain.