VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-combine-usecontext-with-usereducer/

⇱ How to combine useContext with useReducer? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to combine useContext with useReducer?

Last Updated : 23 Jul, 2025

Combining useContext with useReducer in React allows you to manage a global state more effectively by providing a centralized state management solution.

How to combine useContext with useReducer?

  • Create a Context: First, you need to create a context to hold your global state and provide it to your component tree. You can use the React.createContext() function for this purpose.
  • Define a Reducer: Define a reducer function that specifies how state transitions should occur in response to dispatched actions. The reducer takes the current state and an action as arguments and returns the new state.
  • Use useReducer Hook: Inside your component, use the useReducer hook to manage state transitions based on dispatched actions. This hook returns the current state and a dispatch function, which is used to send actions to the reducer.
  • Use useContext Hook: Use the useContext hook to access the state and dispatch function provided by the context.

Example: Below is an example of combining useContext with useReducer.

  • We create a context called GlobalStateContext.
  • We define a reducer function that manages state transitions for a simple counter.
  • We use the useReducer hook inside the GlobalStateProvider component to manage the global state.
  • We provide the state and dispatch function to the context using GlobalStateContext.Provider.
  • We use useContext to access the state and dispatch function in the Counter component.
  • Finally, we wrap our Counter component with the GlobalStateProvider in the App component to make the global state available to it.

Output:

👁 gfg41
Output


Comment