JavaScript and React course · Module 3: State and Events

Updating State - Patterns and Pitfalls

7 min read ·
In this lesson8

Imagine that the navigation systems of your spaceship operate based on state data - speed, course, fuel level. Every update to these parameters must be precise, because even a small error can throw the ship out of orbit. In React, state updates follow similar rules - you must know the patterns for safe updates so your application behaves predictably.

Functional update vs direct value

When you call setState, you have two options. The first is to pass a new value directly:

setCount(count + 1);

The second is a functional update - passing a function that receives the previous state value:

setCount(prev => prev + 1);

Why does this matter? React batches state updates (batching) and does not execute them immediately. If you call setCount(count + 1) multiple times in a single handler, each call sees the same value of count:

function FuelGauge() {
  const [fuel, setFuel] = useState(50);

  const handleTripleBoost = () => {
    // All three see the same value of fuel!
    // Result: fuel will increase by only 10, not 30
    setFuel(fuel + 10);
    setFuel(fuel + 10);
    setFuel(fuel + 10);
  };

  const handleTripleBoostCorrect = () => {
    // Each call receives the current value
    // Result: fuel will increase by 30
    setFuel(prev => prev + 10);
    setFuel(prev => prev + 10);
    setFuel(prev => prev + 10);
  };

  return (
    <div>
      <p>Fuel: {fuel}%</p>
      <button onClick={handleTripleBoost}>Boost (incorrect)</button>
      <button onClick={handleTripleBoostCorrect}>Boost (correct)</button>
    </div>
  );
}

Rule: Always use functional updates (prev => ...) when the new value depends on the previous one.

Multiple state variables vs a single object

You have two strategies for storing state in a component. The first is separate state variables:

function ShipDashboard() {
  const [speed, setSpeed] = useState(0);
  const [altitude, setAltitude] = useState(0);
  const [heading, setHeading] = useState(0);

  // Each variable updated independently
  const accelerate = () => setSpeed(prev => prev + 10);
  const climb = () => setAltitude(prev => prev + 100);

  return (
    <div>
      <p>Speed: {speed} km/s | Altitude: {altitude} km | Heading: {heading}°</p>
      <button onClick={accelerate}>Accelerate</button>
      <button onClick={climb}>Climb</button>
    </div>
  );
}

The second is state in an object - useful when the data is related:

function ShipDashboard() {
  const [navigation, setNavigation] = useState({
    speed: 0,
    altitude: 0,
    heading: 0
  });

  // IMPORTANT: always copy the entire object with the spread operator!
  const accelerate = () => {
    setNavigation(prev => ({ ...prev, speed: prev.speed + 10 }));
  };

  return (
    <div>
      <p>Speed: {navigation.speed} km/s</p>
      <button onClick={accelerate}>Accelerate</button>
    </div>
  );
}

When to use which?

  • Separate useState - when values change independently of each other
  • Object in useState - when values logically belong together (e.g., a form, x/y position)

Most common mistakes - state mutation

In React, state is immutable. Never modify state directly - always create a new copy. It is like a safety rule on a spaceship: you do not edit the ship's log, you just add a new entry.

Mistake 1: push instead of spread for arrays

function MissionLog() {
  const [logs, setLogs] = useState(["Mission started"]);

  const addLog = (entry) => {
    // MISTAKE: push mutates the existing array!
    // React will not detect the change and will not re-render the component
    logs.push(entry);
    setLogs(logs);
  };

  const addLogCorrect = (entry) => {
    // Spread creates a new array
    setLogs(prev => [...prev, entry]);
  };

  return (
    <div>
      <button onClick={() => addLogCorrect("New entry")}>
        Add Entry
      </button>
      {logs.map((log, i) => <p key={i}>{log}</p>)}
    </div>
  );
}

Mistake 2: directly changing object properties

function CrewMember() {
  const [member, setMember] = useState({
    name: "Captain Nova",
    rank: "Captain",
    missions: 12
  });

  const promote = () => {
    // MISTAKE: direct mutation of the object
    member.rank = "Admiral";
    setMember(member);
  };

  const promoteCorrect = () => {
    // Creating a new object with the spread operator
    setMember(prev => ({ ...prev, rank: "Admiral" }));
  };

  return (
    <div>
      <p>{member.name} - {member.rank}</p>
      <button onClick={promoteCorrect}>Promote</button>
    </div>
  );
}

Stale closures - the closure trap

A closure is a situation where a function "remembers" variables from the moment it was created. In React, this can lead to reading outdated state:

function CountdownTimer() {
  const [seconds, setSeconds] = useState(10);
  const [running, setRunning] = useState(false);

  const startCountdown = () => {
    // seconds is "frozen" from the moment of the click!
    // Every interval sees the same value
    setInterval(() => {
      setSeconds(seconds - 1); // always 10 - 1 = 9
    }, 1000);
  };

  const startCountdownCorrect = () => {
    setRunning(true);
    // Functional update always uses the current value
    setInterval(() => {
      setSeconds(prev => Math.max(prev - 1, 0));
    }, 1000);
  };

  return (
    <div>
      <p>Countdown: {seconds}s</p>
      <button onClick={startCountdownCorrect} disabled={running}>Start</button>
    </div>
  );
}

The button with disabled={running} will not let you start a second interval, and Math.max(prev - 1, 0) stops the counter at zero. The interval itself keeps running, though, until you stop it with clearInterval - you will learn proper timer cleanup in the module on effects (useEffect).

Batching - grouping updates

React 18+ automatically batches multiple state updates in a single event handler, performing only one re-render. It is like the onboard computer that collects all sensor reports and updates the display once, instead of refreshing it after each sensor:

function NavigationUpdate() {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [velocity, setVelocity] = useState(0);
  const [status, setStatus] = useState("idle");

  const handleJump = () => {
    // React batches these 3 updates into one render
    setPosition({ x: 100, y: 200 });
    setVelocity(9999);
    setStatus("hyperjump");
    // The component renders ONCE, not three times!
  };

  return (
    <div>
      <p>Position: ({position.x}, {position.y})</p>
      <p>Velocity: {velocity} | Status: {status}</p>
      <button onClick={handleJump}>Hyperspace Jump</button>
    </div>
  );
}

Practical state update patterns

Here are some patterns that will come in handy on board the React ship:

// Removing an element from an array
setItems(prev => prev.filter(item => item.id !== idToRemove));

// Updating one element in an array
setItems(prev => prev.map(item =>
  item.id === targetId ? { ...item, status: "done" } : item
));

// Toggle (switching a boolean)
setIsActive(prev => !prev);

// Adding an element to the beginning of an array
setMessages(prev => [newMessage, ...prev]);

// Incrementing with a limit
setFuel(prev => Math.min(prev + 10, 100));

Lazy state initialization

The initial value is only needed on the first render. But if you call a function inside the useState parentheses, it runs on every render, even though React uses its result only the first time:

// WRONG - computeStarMap() runs on every render
const [stars, setStars] = useState(computeStarMap());

For an expensive computation (e.g. building a star map from thousands of points), pass the function itself - React calls it only once, on the first render:

// CORRECT - the initializer function runs only on the first render
const [stars, setStars] = useState(() => computeStarMap());

You pass the function (() => computeStarMap() or just computeStarMap), not its result - React remembers the value and does not compute it again on later renders.

Summary

Updating state in React - key principles:

  1. Functional update (prev => prev + 1) - use when the new value depends on the previous one
  2. Never mutate state - always create new arrays/objects (spread operator)
  3. Batching - React groups updates and renders the component once
  4. Stale closures - in callbacks and timers, use functional updates
  5. Multiple useState vs object - depends on the logical relationship of the data
  6. Lazy initialization - useState(() => compute()) computes the initial value only once
Code for this lesson: App.jsx
import React, { useState } from 'react';

function FuelManager() {
  // Separate state variables
  const [fuel, setFuel] = useState(50);
  const [oxygen, setOxygen] = useState(100);

  // State as an object
  const [position, setPosition] = useState({ x: 0, y: 0, z: 0 });

  // State as an array
  const [logs, setLogs] = useState([
    { id: 1, message: 'System started', time: '00:00' }
  ]);

  const [newLog, setNewLog] = useState('');

  // Functional update (prev =>)
  const boostFuel = () => {
    setFuel(prev => Math.min(prev + 10, 100));
  };

  const consumeFuel = () => {
    setFuel(prev => Math.max(prev - 15, 0));
  };

  // Object update with spread
  const moveShip = (axis, delta) => {
    setPosition(prev => ({ ...prev, [axis]: prev[axis] + delta }));
  };

  // Adding to an array (spread, not push!)
  const addLog = () => {
    if (!newLog.trim()) return;
    const now = new Date().toLocaleTimeString().slice(0, 5);
    setLogs(prev => [...prev, {
      id: Date.now(),
      message: newLog,
      time: now
    }]);
    setNewLog('');
  };

  // Removing from an array (filter)
  const removeLog = (id) => {
    setLogs(prev => prev.filter(log => log.id !== id));
  };

  // Triple boost - comparing the wrong and correct approach
  const brokenTripleBoost = () => {
    // fuel is "frozen" - all 3 see the same value
    setFuel(fuel + 5);
    setFuel(fuel + 5);
    setFuel(fuel + 5);
  };

  const correctTripleBoost = () => {
    // Each call sees the current value
    setFuel(prev => Math.min(prev + 5, 100));
    setFuel(prev => Math.min(prev + 5, 100));
    setFuel(prev => Math.min(prev + 5, 100));
  };

  return (
    <div style={{ fontFamily: 'Arial, sans-serif', padding: '20px', maxWidth: '700px', margin: '0 auto' }}>
      <h1 style={{ textAlign: 'center', color: '#667eea' }}>State update patterns</h1>

      {/* Fuel section */}
      <div style={{ padding: '16px', marginBottom: '16px', backgroundColor: '#f0f4ff', borderRadius: '12px' }}>
        <h3>Fuel: {fuel}%</h3>
        <div style={{ height: '20px', backgroundColor: '#ddd', borderRadius: '10px', overflow: 'hidden' }}>
          <div style={{
            height: '100%', width: fuel + '%',
            backgroundColor: fuel > 30 ? '#4caf50' : '#f44336',
            transition: 'width 0.3s'
          }} />
        </div>
        <div style={{ marginTop: '10px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
          <button onClick={boostFuel} style={btnStyle('#4caf50')}>+10 (functional)</button>
          <button onClick={consumeFuel} style={btnStyle('#f44336')}>-15 (functional)</button>
          <button onClick={brokenTripleBoost} style={btnStyle('#ff9800')}>3x +5 (wrong)</button>
          <button onClick={correctTripleBoost} style={btnStyle('#2196f3')}>3x +5 (correct)</button>
        </div>
      </div>

      {/* Position section (object) */}
      <div style={{ padding: '16px', marginBottom: '16px', backgroundColor: '#f0fff4', borderRadius: '12px' }}>
        <h3>Ship position (object with spread)</h3>
        <p>X: {position.x} | Y: {position.y} | Z: {position.z}</p>
        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
          <button onClick={() => moveShip('x', 10)} style={btnStyle('#667eea')}>X +10</button>
          <button onClick={() => moveShip('y', 10)} style={btnStyle('#667eea')}>Y +10</button>
          <button onClick={() => moveShip('z', 10)} style={btnStyle('#667eea')}>Z +10</button>
          <button onClick={() => setPosition({ x: 0, y: 0, z: 0 })} style={btnStyle('#999')}>Reset</button>
        </div>
      </div>

      {/* Logs section (array) */}
      <div style={{ padding: '16px', backgroundColor: '#fff8f0', borderRadius: '12px' }}>
        <h3>Ship log (array with spread)</h3>
        <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>
          <input
            value={newLog}
            onChange={e => setNewLog(e.target.value)}
            placeholder="New entry..."
            style={{ flex: 1, padding: '8px', borderRadius: '8px', border: '1px solid #ddd' }}
          />
          <button onClick={addLog} style={btnStyle('#ff9800')}>Add</button>
        </div>
        {logs.map(log => (
          <div key={log.id} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '8px 12px', marginBottom: '6px', backgroundColor: '#fff',
            borderRadius: '8px', border: '1px solid #eee'
          }}>
            <span><strong>[{log.time}]</strong> {log.message}</span>
            <button onClick={() => removeLog(log.id)} style={{
              background: 'none', border: 'none', color: '#f44336', cursor: 'pointer', fontSize: '16px'
            }}>x</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function btnStyle(bg) {
  return {
    padding: '8px 16px', backgroundColor: bg, color: 'white',
    border: 'none', borderRadius: '8px', cursor: 'pointer', fontSize: '13px'
  };
}

export default function App() {
  return <FuelManager />;
}

Remember: State in React is like the ship's log - you never edit it, you just create a new entry based on the previous one!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why should you use functional updates (prev => prev + 1) when calling setState multiple times in a single handler?

  2. 2. Why is the following code incorrect? const [items, setItems] = useState(['A', 'B']); items.push('C'); setItems(items);

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange what happens when React batches multiple state updates:

  1. QuestionFunctional setState Update
  2. QuestionState Mutation in React
  3. QuestionStopping propagation - what appears in the console?
  4. Put in orderState Update Batching Process

Useful articles