DEV Community

Sajin Joe J
Sajin Joe J

Posted on

React useReducer – Interview Questions & Answers

Q1. What is useReducer in React?

  • useReducer is a React Hook used to manage state using a reducer function and actions.
  • It is useful when state logic becomes complex or when multiple actions update the same state.
const [state, dispatch] = useReducer(reducer, initialState);
Enter fullscreen mode Exit fullscreen mode

state – current state value.
dispatch – function used to send an action.
reducer – function that decides how state changes.
initialState – initial value of the state.

Q2. What is a reducer function?
A reducer is a function that takes two arguments:

  1. Current state
  2. Action It returns the updated state.

syntax:

function reducer(state, action) {
    return newState;
}
Enter fullscreen mode Exit fullscreen mode

Example:

function reducer(state, action) {
    switch (action.type) {
        case "Increment":
            return state + 1;

        case "Decrement":
            return state - 1;

        case "Reset":
            return 0;

        default:
            return state;
    }
}
Enter fullscreen mode Exit fullscreen mode

Q3. What is dispatch?
dispatch is a function used to send an action to the reducer.
Q4. What is an action in useReducer?
An action is an object that describes what we want to do with the state.
Q5. What is the purpose of action.type?
action.type identifies which action was dispatched.

Q6 Practical coding interview – Counter using useReducer
This is one of the most common coding questions for React interviews.
Requirements

  • Increment
  • Decrement
  • Reset
  • Increment by 5
import React, { useReducer } from 'react';

function reducer(state, action) {
    switch (action.type) {
        case "Increment":
            return state + 1;

        case "Decrement":
            return state - 1;

        case "IncrementByFive":
            return state + action.payload;

        case "Reset":
            return 0;

        default:
            return state;
    }
}

function App() {
    const [count, dispatch] = useReducer(reducer, 0);

    return (
        <>
            <h1>{count}</h1>

            <button onClick={() => dispatch({ type: "Increment" })}>
                Increment
            </button>

            <button onClick={() => dispatch({ type: "Decrement" })}>
                Decrement
            </button>

            <button onClick={() => dispatch({
                type: "IncrementByFive",
                payload: 5
            })}>
                +5
            </button>

            <button onClick={() => dispatch({ type: "Reset" })}>
                Reset
            </button>
        </>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)