Friday, 18 Jul 2025
  • My Interests
  • My Saves
  • Try Intents
Subscribe
improve-logo improve-logo
  • Home
  • HTML
    What is Symentic HTML

    What is Symentic HTML?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor

    Difference between HTML Tag and HTML Element in HTML?

    By Chief Editor

    What are the different types of HTML tags?

    By Chief Editor

    What are the async and defer attributes in the “script” tag?

    By Chief Editor

    What is a Meta Tag in HTML?

    By Chief Editor
  • JavaScript

    What is Arrow and Normal Function in JavaScript?

    By Chief Editor

    Explain Call, Apply and Bind in JavaScript.

    By Chief Editor

    What is Scope in JavaScript?

    By Chief Editor

    What are the Rest and Spread operators in JavaScript?

    By Chief Editor

    Difference between document.createElement and document.createElementFragement in JavaScript?

    By Chief Editor

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor
  • Frontend Interview

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor

    Explain Deep Copy and Shallow Copy in JavaScript.

    By Chief Editor

    Is JavaScript a synchronous or asynchronous language?

    By Chief Editor

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor
  • Backend Interview

    What is Synthetic Event?

    By Chief Editor

    What is the this Keyword in JavaScript?

    By Chief Editor

    What is Redux, and how does it work?

    By Chief Editor

    Difference Between position: relative and position: absolute in CSS

    By Chief Editor

    System Design and Frontend System Design: An In-depth Overview

    By Chief Editor

    What is Life Cycle method in React?

    By Chief Editor
  • Nodejs
  • Frontend Interview
  • Backend Interview
  • React Interview
  • JavaScript Interview
  • Contacts Us
  • Advertise with Us
  • Complaint
  • Privacy Policy
  • Cookie Policy
  • Donate
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • HTML
  • Frontend Interview
  • CSS
  • Redux
  • Javascript
  • System Design
Font ResizerAa
ImproveImprove
  • My Saves
  • My Interests
  • My Feed
  • History
  • Technology
Search
  • Homepage
  • Pages
    • Home
    • Blog Index
    • Contact Us
    • Search Page
    • 404 Page
  • Features
    • Post Headers
    • Layout
  • Personalized
    • My Feed
    • My Saves
    • My Interests
    • History
  • About
  • Categories
    • Technology
  • Categories
Have an existing account? Sign In
Follow US
© 2022 Code Reveals Inc. All Rights Reserved.

Home Explain the uesReducer and useContext hooks in React

ReactJS

Explain the uesReducer and useContext hooks in React

Chief Editor
Last updated: February 16, 2025 6:11 pm
Chief Editor
Share
SHARE

useReducer and useContext Hooks in React


1. useReducer Hook

Purpose:

The useReducer hook is an alternative to useState.
It is used when state logic is complex, involves multiple sub-values, or when the next state depends on the previous state.

Contents
1. useReducer Hook2. useContext HookCombining useReducer and useContextKey Differences:When to Use Which:Summary:

Syntax:

javascriptCopyEditconst [state, dispatch] = useReducer(reducer, initialState);
PartDescription
stateCurrent state value.
dispatchFunction to send actions to the reducer.
reducerFunction to determine state updates based on actions.
initialStateInitial state value.

Reducer Function:

javascriptCopyEditfunction reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

Example:

javascriptCopyEditimport { 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:
      return state;
  }
}

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

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}

Key Points:

FeatureDescription
Used for Complex StateBest for state involving multiple sub-values or complex transitions.
Action-based UpdatesUses actions to update state.
Predictable State UpdatesState changes follow a strict logic defined in reducer.
Similar to Redux (but local)Similar in concept to Redux reducers, but local to the component.


2. useContext Hook

Purpose:

The useContext hook is used to consume values from a React Context.

Context provides a way to pass data through the component tree without having to pass props manually at every level.


Syntax:

javascriptCopyEditconst value = useContext(MyContext);
PartDescription
MyContextContext object created using React.createContext().
valueCurrent value of the context.

Example:

javascriptCopyEditimport { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemedComponent() {
  const theme = useContext(ThemeContext);

  return <p>Current Theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedComponent />
    </ThemeContext.Provider>
  );
}

Key Points:

FeatureDescription
Avoids Prop DrillingHelps avoid passing props down through multiple levels.
Global-like StateUseful for global values like themes, auth status, etc.
Simplifies ConsumptionNo need for Context.Consumer → useContext is simpler.
Works with ProviderMust wrap components with Context.Provider to provide the value.

Combining useReducer and useContext

Often, useReducer is used together with useContext to create a global state management solution similar to Redux.

Example:

javascriptCopyEditimport { createContext, useReducer, useContext } from 'react';

// 1. Create Context
const CounterContext = createContext();

// 2. Reducer Function
function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// 3. Provider Component
function CounterProvider({ children }) {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });

  return (
    <CounterContext.Provider value={{ state, dispatch }}>
      {children}
    </CounterContext.Provider>
  );
}

// 4. Consumer Component
function CounterDisplay() {
  const { state } = useContext(CounterContext);
  return <p>Count: {state.count}</p>;
}

function CounterButtons() {
  const { dispatch } = useContext(CounterContext);
  return (
    <>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}

// 5. App Component
function App() {
  return (
    <CounterProvider>
      <CounterDisplay />
      <CounterButtons />
    </CounterProvider>
  );
}

Key Differences:

HookPurposeCommon Use Case
useReducerManages complex state logicWhen state has multiple sub-values or complex updates.
useContextAccesses shared data across componentsWhen passing data deeply through component trees (e.g., themes, auth).

When to Use Which:

SituationHook to Use
Simple State (e.g., boolean, counter)useState
Complex State (e.g., object, multiple values)useReducer
Share State Across ComponentsuseContext
Global State with Complex LogicuseReducer + useContext

Summary:

HookPurposeCommon Pairing
useReducerManages complex state logicOften used with useContext
useContextAccesses context values without prop drillingCan pair with useReducer for global state

Let me know if you need more help with these hooks or React concepts! 🚀😊

Share This Article
Email Copy Link Print
Previous Article Explain the useState and useEffect hooks in React
Next Article What is Redux, and how does it work?
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Your Trusted Source for Accurate and Timely Updates!

Our commitment to accuracy, impartiality, and delivering breaking news as it happens has earned us the trust of a vast audience. Stay ahead with real-time updates on the latest events, trends.
FacebookLike
XFollow
InstagramFollow
YoutubeSubscribe
LinkedInFollow
QuoraFollow
- Advertisement -
Ad imageAd image

Popular Posts

What are controlled and uncontrolled components in React?

When working with form inputs in React, you will often hear the terms Controlled Components…

By Chief Editor

How Can You Share Data Between Components in React?

In React, there are several ways to share data between components, depending on the relationship…

By Chief Editor

Difference Between position: relative and position: absolute in CSS

Propertyposition: relativeposition: absoluteDefinitionThe element is positioned relative to its original position in the normal document…

By Chief Editor

You Might Also Like

ReactJS

What is localization in React?

By Chief Editor
ReactJS

What are the drawbacks of React?

By Chief Editor
How-to-Improve-the-Performance-of-React-Applications
ReactJSReact Interview

Lazy Loading in React.js: Boosting Performance and Reducing Load Time

By Chief Editor
ReactJS

What is a Function Component in React?

By Chief Editor
improve-logo

Code Reveals is a cutting-edge software development company dedicated to delivering high-quality, scalable, and innovative solutions for businesses of all sizes. Our team of expert developers, designers, and engineers specializes in creating custom software, web applications, mobile apps, and enterprise solutions that are tailored to meet the unique needs of our clients.

Most Famous
  • HTML
  • CSS
  • JavaScript
  • Node
Top Categories
  • Frontend Interview
  • Backend Interview
  • React Interview
  • JavaScript Interview
Usefull Links
  • Contacts Us
  • Advertise with Us
  • Complaint
  • Privacy Policy
  • Cookie Policy
  • Donate

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?