Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Fundamentals
  1. 1.Introduction to React & Development Environment
  2. 2.JSX, Components & Props
  3. 3.Managing Component State with useState
  4. 4.Event Handling & Conditional Rendering
  5. 5.Rendering Lists & Basic useEffect
  6. 6.Deep Dive into useEffect Hook
  7. 7.useRef and useReducer for Complex State
  8. 8.Optimizing Performance with useMemo & useCallback
  9. 9.Context API & Custom Hooks for Reusability
  10. 10.Client-Side Routing with React Router
  11. 11.Forms, Validation & Data Fetching Patterns
  12. 12.Advanced Performance Optimization & Reconciliation
  13. 13.State Management Libraries (Redux Toolkit & Alternatives)
  14. 14.Testing React Components with Jest & React Testing Library
  15. 15.Advanced React Features & Modern Concepts
React Fundamentals
07

React · Lesson 7 of 15 · 4 min

useRef and useReducer for Complex State

This is how you explain when useState isn't enough, and prove you know how to manage state that isn't just a boolean or a string.

After this, you'll know exactly when to reach for useRef or useReducer. More importantly, you'll be able to articulate the trade-offs to an interviewer, which is a strong signal of a senior mindset. We're moving beyond simple state toggles into managing component logic that scales.

useRef is your escape hatch

Use useRef for two main reasons: accessing a DOM node directly, or keeping a mutable value that doesn't trigger a re-render. Think of it as an instance variable on a class component.

The most common case is grabbing a DOM element. You might need to focus an input, measure its dimensions, or trigger an imperative API like on a <video> element. React's declarative model doesn't cover these, so you need a ref to break out of it.

The second case is for data that needs to persist across renders but whose changes should not cause a re-render. The classic example is storing a timer ID from setTimeout or setInterval. You need to access the ID later to clear it, but you don't want the component to re-render every time you set a new timer.

The trap: Candidates often confuse it with useState. The key difference is that updating a ref's .current property is synchronous and does not trigger a re-render. An update from useState is asynchronous and schedules a re-render. If you need the UI to react to a data change, you need state.

Never assign to .current during the render phase. A component's render function should be pure. Mutations should only happen in event handlers or useEffect.

When to reach for useReducer

Look for components with multiple useState hooks that manage related data. If you see const [data, setData] = useState(...), const [isLoading, setIsLoading] = useState(false), and const [error, setError] = useState(null), you have a state machine. Managing these transitions with separate state setters can get messy and bug-prone.

This is a code smell. Your logic for a single user action, like fetching data, is scattered. You have to remember to call setIsLoading(true), then setError(null), then setData(...) in the right order.

useReducer lets you consolidate this. It moves the state transition logic from scattered event handlers into a single, pure function.

The rule of thumb: if your next state depends on the previous state in a complex way, or if multiple state values change together in response to a single event, useReducer will make your code more robust and predictable.

The reducer pattern: dispatch, action, new state

The flow is simple and predictable, which is the whole point.

  1. An event handler calls dispatch with an action object. An action is just a plain object describing what happened, like { type: 'FETCH_SUCCESS', payload: data }.
  2. React feeds the current state and that action into your reducer function.
  3. Your reducer function calculates the next state based on the current state and the action, and returns a brand new state object.
  4. React detects the new state object and triggers a re-render.

The trap: The reducer must be a pure function. Never mutate the state argument. If you do, React might not detect the change, and your component won't re-render. Always return a new object.

Wrong: state.status = 'loading'; return state; Right: return { ...state, status: 'loading' };

A reducer for a multi-field form

A form is a perfect use case. You have multiple fields, plus submission status (idle, pending, error). Managing this with useState gets tangled quickly. With useReducer, the logic is clean and centralized.

This example shows how a reducer can handle updates for different fields and a global form status from a single dispatch function.

import React, { useReducer } from 'react';

type State = {
  name: string;
  email: string;
  status: 'IDLE' | 'PENDING' | 'SUCCESS' | 'ERROR';
};

type Action =
  | { type: 'SET_FIELD'; field: 'name' | 'email'; payload: string }
  | { type: 'SUBMIT' }
  | { type: 'RESET' };

const initialState: State = { name: '', email: '', status: 'IDLE' };

function formReducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_FIELD':
      return { ...state, [action.field]: action.payload };
    case 'SUBMIT':
      return { ...state, status: 'PENDING' };
    case 'RESET':
      return initialState;
    default:
      return state;
  }
}

function SignUpForm() {
  const [state, dispatch] = useReducer(formReducer, initialState);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    dispatch({ type: 'SUBMIT' });
    // In a real app, an effect would listen for the 'PENDING' status
    // to perform the async request and dispatch success/error actions.
    console.log('Submitting:', state);
  };
  
  // The component's JSX would then render based on `state`
  // and call `dispatch` in its input `onChange` handlers.
}

How does this relate to Redux? An interviewer might ask. Here's your answer: useReducer is like a local, component-level Redux. It implements the same core pattern (action -> reducer -> new state) but without the boilerplate of a global store, middleware, or complex setup. For state that's confined to one component or a small part of the tree, useReducer is the right tool. When you need to manage truly global application state, that's when you reach for a library like Redux or Zustand.

Try it

Find a component you've written that uses three or more useState hooks for related data (like a form's inputs, loading state, and error state). Refactor it to use a single useReducer. Notice how the event handlers simplify and the state logic is now centralized in one place.

Next: Optimizing Performance with useMemo & useCallback.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Deep Dive into useEffect Hook

Next

Optimizing Performance with useMemo & useCallback