Monday, 2 Jun 2025
  • My Feed
  • My Interests
  • My Saves
  • History
  • Blog
Subscribe
Code Reveals
  • Home
  • HTML

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

    By admin

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

    By admin

    What is Doctype HTML in HTML?

    By admin

    What is a Meta Tag in HTML?

    By admin
    What is Symentic HTML

    What is Symentic HTML?

    By admin

    What is Block level Element and Inline Level Element?

    By admin
  • JavaScript

    What is hoisting in JavaScript with an example?

    By admin

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

    By admin

    How to Reverse a String in JavaScript: Two Essential Methods

    By admin

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

    By admin

    What is memoization in JavaScript?

    By admin

    What are the Rest and Spread operators in JavaScript?

    By admin
  • Frontend Interview

    Difference Between position: relative and position: absolute in CSS

    By admin

    What is Symentic HTML?

    By admin

    Explain Deep Copy and Shallow Copy in JavaScript.

    By admin

    What is Block level Element and Inline Level Element?

    By admin

    What is Position in CSS?

    By admin

    Is JavaScript a synchronous or asynchronous language?

    By admin
  • Backend Interview

    What are the Rest and Spread operators in JavaScript?

    By admin

    What is Doctype HTML in HTML?

    By admin

    What is localization in React?

    By admin

    What is Flex Box in CSS?

    By admin

    How Can You Share Data Between Components in React?

    By admin

    Difference between display none and visibility hidden in CSS?

    By admin
  • Other
    • Contact Us
  • Frontend Interview
  • Backend Interview
  • React Interview
  • JavaScript Interview
  • Contacts Us
  • Advertise with Us
  • Complaint
  • Privacy Policy
  • Cookie Policy
  • Submit a Tip
  • 🔥
  • ReactJS
  • JavaScript
  • JavaScript Interview
  • React Interview
  • HTML
  • Frontend Interview
  • CSS
  • Redux
  • Javascript
  • System Design
Font ResizerAa
Code RevealsCode Reveals
  • 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 Blog Explain the uesReducer and useContext hooks in React
ReactJS

Explain the uesReducer and useContext hooks in React

admin
Last updated: February 16, 2025 6:11 pm
admin
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 is props drilling in React?

Props Drilling is a situation in React where data (props) needs to be passed through…

By admin

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

Difference Between HTML and HTML5 HTML (HyperText Markup Language) is the standard language used to…

By admin

How Does React Work?

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

By admin

You Might Also Like

ReactJS

What is React Fiber and its importance in react?

By admin
ReactJS

What is a Function Component in React?

By admin
Mastering Star Rating Systems: Best Practices and Optimized Code Examples
React InterviewReactJS

Mastering Star Rating Systems: Best Practices and Optimized Code Examples

By admin
ReactJS

What are controlled and uncontrolled components in React?

By admin

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
  • Submit a Tip

©2025  Code Reveals Inc. All Rights Reserved.

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?