useReducer in React

Expert-Level Explanation

useReducer is a React hook that is used for managing complex state logic in functional components. It's an alternative to useState, providing more direct control over the state. You pass it a reducer function and an initial state. The reducer function takes the current state and an action as arguments and returns the new state. It's particularly useful when the next state depends on the previous one or when managing a state that involves multiple sub-values.

Creative Explanation

Imagine useReducer as the central command system on a space shuttle. This system receives specific commands (actions) and decides how to adjust various systems of the shuttle (state). Each command goes through a process (reducer function) that determines how to change the state based on the current state and the received command.

Practical Explanation with Code

Example of using useReducer:

import React, { useReducer } from 'react';

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, { count: 0 });

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}

In this Counter component, useReducer manages the state based on the dispatched actions.

Real-World Example

In a to-do list application, useReducer can manage the list's state, handling actions like adding a task, removing a task, or marking a task as completed. The reducer function updates the state based on these actions, allowing for complex state logic to be handled in a structured way.

Did you find this article valuable?

Support InterviewPro: Master Tech Fundamentals by becoming a sponsor. Any amount is appreciated!