Wednesday, 15 Oct 2025
  • My Interests
  • My Saves
  • Try Intents
Subscribe
Focus - Code Reveals
  • Home
  • HTML

    What is Block level Element and Inline Level Element?

    By Chief Editor

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

    By Chief Editor
    What is Symentic HTML

    What is Symentic HTML?

    By Chief Editor

    What is Doctype HTML in HTML?

    By Chief Editor

    What is a Meta Tag in HTML?

    By Chief Editor

    What is the difference between “HTML” and “HTML5”?

    By Chief Editor
  • JavaScript

    What are the map, filter, and reduce methods in JavaScript?

    By Chief Editor

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

    By Chief Editor

    What is Arrow and Normal Function in JavaScript?

    By Chief Editor

    Explain Call, Apply and Bind in JavaScript.

    By Chief Editor

    What is a Promise in JavaScript, and what are its parameters?

    By Chief Editor

    What is memoization in JavaScript?

    By Chief Editor
  • Frontend Interview

    How to Reverse a String in JavaScript: Two Essential Methods

    By Chief Editor

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    What is Block level Element and Inline Level Element?

    By Chief Editor

    Is JavaScript a synchronous or asynchronous language?

    By Chief Editor

    What is Position in CSS?

    By Chief Editor

    What is Symentic HTML?

    By Chief Editor
  • Backend Interview

    Understanding the Event Loop in Node.js: A Complete Beginner’s Guide

    By Chief Editor

    What is a Closure in JavaScript?

    By Chief Editor

    What are the Lexical Scope in JavaScript?

    By Chief Editor

    Explain var let and const in JavaScript with Example.

    By Chief Editor

    What is Higher Order Component in React?

    By Chief Editor

    How Does React Work?

    By Chief Editor
  • Nodejs
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • HTML
  • CSS
  • Redux
  • Backend Interview
  • NodeJS
Font ResizerAa
Focus - Code RevealsFocus - Code Reveals
  • My Saves
  • My Interests
  • My Feed
  • History
  • Technology
Search
  • Homepage
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • HTML
  • CSS
  • Backend Interview
Have an existing account? Sign In
Follow US
© 2022 Code Reveals Inc. All Rights Reserved.
Home Blog Explain the uesReducer and useContext hooks in React
ReactJS

Explain the uesReducer and useContext hooks in React

Chief Editor
Last updated: July 30, 2025 5:20 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 the Rest and Spread operators in JavaScript?

Rest and Spread Operators in JavaScript (...) The Rest Operator and Spread Operator both use…

By Chief Editor

Understanding the Event Loop in Node.js: A Complete Beginner’s Guide

Node.js is known for its ability to handle high-performance, non-blocking I/O operations, making it a…

By Chief Editor

How Does React Work?

React is a JavaScript library used for building user interfaces, particularly for single-page applications (SPAs).It…

By Chief Editor

You Might Also Like

ReactJS

What is Synthetic Event?

By Chief Editor
ReactJS

What is a Function Component in React?

By Chief Editor
ReactJS

What are the drawbacks of React?

By Chief Editor
ReactJSRedux

What is middleware, and what is React Thunk?

By Chief Editor

Focus by CodeReveals is your dedicated platform for mastering tech interviews and advancing your development skills. Whether you’re aiming to become a Frontend Developer, Backend Developer, or simply preparing for your next big interview, we’re here to guide you every step of the way.

Our mission is to help aspiring developers gain real-world knowledge, build confidence, and succeed in technical interviews. We offer structured content, curated interview questions, coding challenges, and practical guidance — all designed by experienced professionals who understand what top tech companies are looking for.

At Improve, we don’t just teach — we prepare you to think like a developer, solve like an engineer, and present like a pro.

Join us and start improving today — because your dream tech job is within reach

Most Famous
  • HTML
  • CSS
  • JavaScript
  • NodeJS
Top Categories
  • JavaScript Interview
  • React Interview
  • Frontend Interview
  • Backend Interview
Usefull Links
  • Contact Us
  • Advertise with Us
  • Complaint
  • Cookies Policy
  • Privacy Policy
  • Donate

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?