React useReducer with useContext

Nitish Thakur
3 min readJul 6, 2022

In react if we have data in the parent component, pass that data to the child components and also want to update that data. The simpler way we used is props by using props we can share data b/w child components and call methods from child to parent components.

In this article, we will use “useReducer” and “useContext” hooks to share data b/w child components and update that data from child components without props.

  1. useReducer: useReducer is the alternative to useState and is preferred to use when you have some complex states or when the next state value depends on the previous one. useReducer also let’s optimize performance for components that trigger deep updates.

The “useReducer(reducer, initialState)” hook accepts 2 arguments: the reducer function and the initial state. The hook then returns an array of 2 items: the current state and the dispatch function

simple counter example

This is simple counter example by using “useReducer”

2. useContext: Context is used when some data needs to be accessible by many components at different nesting levels.

In this example first we will create a context:

createContext

and wrap the child components in context provider:

context provider

In child components we will access it by using “useContext” hook:

useContext

Now let’s merge both hooks in a component where we also dispatch actions from nested child components.

let’s take an example of a counter where we update the counter from nested child components.

Parent Component:

parent component

In Parent component we create a context:

next we define a intialstate:

reducer function:

reducer function

In component, we call a useReducer hook: with reducer function and initialState

Next, we wrap child components in a context provider for sharing state and action dispatch:

Now in the child component, we will use “useContext” hook:

on button click we are dispatching an action with type: ‘increment, decrement or reset’.

here is the working example: https://codesandbox.io/s/react-usereducer-with-usecontext-t976pi?file=/src/App.js

Conclusion

useReducer: “useReducer()” fits great with relatively complex state updates (requiring at least 2–3 update actions). For simple state management, simply use useState().

useContext: The context in React is a concept that lets you supply child components with global data, no matter how deep they are in the components tree.

Using the context requires 3 steps: creating, providing, and consuming the context.

--

--