React
useContext is a React hook that allows components to consume values from a
context created by the createContext API. It provides a way to pass data
through the component tree without having to pass props manually at every level.
Basic Example
Here's a basic example of how useContext works:
- Creating a Context
// AppContext.js
import React, { createContext, useState, useContext } from "react";
// Create a context with an initial value
const AppContext = createContext();
// Create a provider component to wrap your app
export const AppProvider = ({ children }) => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
// Value object that will be accessible to consuming components
const value = {
count,
increment,
decrement,
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};
// Custom hook to consume the context
export const useAppContext = () => useContext(AppContext);
In this example:
AppContextis created usingcreateContext().AppProvideris a component that wraps your application and provides the context value (count,increment,decrement).useAppContextis a custom hook that provides easy access to the context value within any component.
- Using the Context in Components
import { useAppContext } from "./AppContext";
const ExampleComponent = () => {
const { count, increment, decrement } = useAppContext();
return (
<div>
{" "}
<p>Count: {count}</p> <button onClick={increment}>Increment</button> <button
onClick={decrement}
>
Decrement
</button>{" "}
</div>
);
};
export default ExampleComponent;
ExampleComponentusesuseAppContextto accesscount,increment, anddecrementfrom the context.- It renders a simple component that displays the count and provides buttons to increment and decrement the count.
-
Wrapping Your App with the Provider
import React from "react";
import { AppProvider } from "./AppContext";
import ExampleComponent from "./ExampleComponent";
const App = () => {
return (
<AppProvider>
{" "}
<div className="App">
{" "}
<h1>Using useContext Example</h1> <ExampleComponent />{" "}
</div>{" "}
</AppProvider>
);
};
export default App;Appwraps the entire application withAppProvider, making the context values (count,increment,decrement) available to all components rendered withinApp.
Explanation
- Context Creation:
createContext()creates a new context object. You can provide an initial value to it. - Provider Component:
AppProvideris a regular React component that usesAppContext.Providerto wrap its children. It provides the context value (count,increment,decrement) to all nested components. - Consuming Context:
useAppContextis a custom hook that usesuseContext(AppContext)to access the current context value wherever it is needed in your application.
Benefits of useContext
- Avoids Prop Drilling: Eliminates the need to pass props through intermediate components that don't need them.
- Simplifies Component Structure: Makes the code cleaner and more maintainable by separating concerns.
- Facilitates State Management: Provides a centralized way to manage and share state across components without using Redux or other state management libraries for simpler use cases.
Using
useContextis particularly beneficial when multiple components need access to the same data or when you want to avoid passing props through several levels of the component tree.