DEV Community

xplodivity
xplodivity

Posted on

Step by step guide on how to use useReducer and useContext together?

Before reading the article, If you are interested in react, JavaScript, or frontend development in general, Do checkout and subscribe xplodivity on youtube.

reducer function

In the example, we start by creating a reducer function that takes the current state and an action as arguments and returns a new state based on the action type. The reducer is responsible for updating the state based on the actions it receives.

create context

Next, we create a context using React.createContext(). The context will allow us to share state and dispatch function between components.

useReducer hook and count provider component

Then we create a CountProvider component that uses the useReducer hook to manage the state. The useReducer hook takes two arguments: the reducer function and an initial state. It returns an array containing the current state and a dispatch function that can be used to dispatch actions to the reducer. The CountProvider component wraps its children with the CountContext.Provider component and passes down the state and dispatch function as context values.

counter component

Finally, we create a Counter component that uses the useContext hook to access the state and dispatch function from the context. The useContext hook takes the context object as an argument and returns the current context value, which is an object with the state and dispatch function in this case. In the Counter component, we display the current count and two buttons that dispatch increment and decrement actions when clicked.

wrap count provider

With this setup, we can use the CountProvider component to wrap any components that need access to the count state and dispatch function. The state and dispatch function will be passed down the component tree via context, allowing the child components to access and update the state without having to pass props down manually.

Top comments (0)