Skip to main content

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:

  1. 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:

  • AppContext is created using createContext().
  • AppProvider is a component that wraps your application and provides the context value (count, increment, decrement).
  • useAppContext is a custom hook that provides easy access to the context value within any component.
  1. 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;
  • ExampleComponent uses useAppContext to access count, increment, and decrement from the context.
  • It renders a simple component that displays the count and provides buttons to increment and decrement the count.
  1. 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;
    • App wraps the entire application with AppProvider, making the context values (count, increment, decrement) available to all components rendered within App.

Explanation

  • Context Creation: createContext() creates a new context object. You can provide an initial value to it.
  • Provider Component: AppProvider is a regular React component that uses AppContext.Provider to wrap its children. It provides the context value (count, increment, decrement) to all nested components.
  • Consuming Context: useAppContext is a custom hook that uses useContext(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 useContext is 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.