The Context API and useReducer Hook

ERP Solutions oodles
3 min readMar 8, 2024

--

Effective state management and data transmission between components may be difficult tasks in the realm of React programming, particularly in larger apps with intricate component trees. Fortunately, React offers strong tools — the Context API and the useReducer hook — to overcome these difficulties.

Understanding the Context API

The Context API allows data to be transmitted through React’s component tree without requiring props to be manually handed down at each level. With it, you can establish a global state that is accessible to any component inside a given scope — usually referred to as a “provider.”

Creating a Context

To construct a context, use React’s createContext function.

import { createContext } from ‘react’;

const MyContext = createContext();

Providing and Consuming Context

Once a context has been created, its value can be supplied by a Provider component and used using the useContext hook.

// App.js

import React from ‘react’;

import { MyContext } from ‘./MyContext’;

import ChildComponent from ‘./ChildComponent’;

function App() {

const value = ‘Hello from Context!’;

return (

<MyContext.Provider value={value}>

<ChildComponent />

</MyContext.Provider>

);

}

export default App;

Also, Read Advanced Search Using Criteria API

// ChildComponent.js

import React, { useContext } from ‘react’;

import { MyContext } from ‘./MyContext’;

function ChildComponent() {

const value = useContext(MyContext);

return <div>{value}</div>;

}

export default ChildComponent;

Introducing the useReducer Hook

The useReducer hook is another useful tool that React provides for managing complex state logic in functional components. It is a superior alternative to useState when handling state objects with several sub-values or when one state depends on another.

The useReducer hook takes a reducer function and a starting state, returns the current state, and provides a dispatch function to update the state.

import React, { useReducer } from ‘react’;

const initialState = { count: 0 };

function reducer(state, action) {

switch (action.type) {

case ‘increment’:

return { count: state.count + 1 };

case ‘decrement’:

return { count: state.count — 1 };

default:

throw new Error();

}

}

function Counter() {

const [state, dispatch] = useReducer(reducer, initialState);

return (

<div>

Count: {state.count}

<button onClick={() => dispatch({ type: ‘increment’ })}>+</button>

<button onClick={() => dispatch({ type: ‘decrement’ })}>-</button>

</div>

);

}

export default Counter;

Combining Context API with useReducer

One of their most helpful use cases is to manage complex state in a global context by combining React’s useReducer hook with the Context API. This approach allows you to focus your state management logic and distribute it across your application without the need for prop drilling.

// StateContext.js

import React, { createContext, useReducer } from ‘react’;

const initialState = {

count: 0

};

function reducer(state, action) {

switch (action.type) {

case ‘increment’:

return { …state, count: state.count + 1 };

case ‘decrement’:

return { …state, count: state.count — 1 };

default:

return state;

}

}

export const StateContext = createContext();

export const StateProvider = ({ children }) => {

const [state, dispatch] = useReducer(reducer, initialState);

return (

<StateContext.Provider value={{ state, dispatch }}>

{children}

</StateContext.Provider>

);

};

Also, Read An Overview of REST and RESTful APIs

// App.js

import React from ‘react’;

import { StateProvider } from ‘./StateContext’;

import Counter from ‘./Counter’;

function App() {

return (

<StateProvider>

<Counter />

</StateProvider>

);

}

export default App;

In this example, we have generated a global state using the useReducer hook, and we are able to make it available to the entire application thanks to the Context API. Consequently, the global state is accessible to all StateProvider components, and they can send actions to update it.

--

--

ERP Solutions oodles
ERP Solutions oodles

Written by ERP Solutions oodles

We are a leading ERP development company in India offers a wide range of ERP software development services to help you grow your business exponentially.

No responses yet