Bird
Raised Fist0
Reactframework~10 mins

Updating state in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Updating state
Initial Render
↓
Display UI with state
↓
User triggers event
↓
Call setState(newValue)
↓
React schedules re-render
↓
Component re-renders with updated state
↓
DOM updates to reflect new state
↓
Wait for next event or interaction
This flow shows how React updates state: user event triggers setState, React re-renders the component, and the UI updates.
Execution Sample
React
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
A simple counter button that increases the count state by 1 each time it is clicked.
Execution Table
StepTriggerState BeforeActionState AfterWhat Re-rendersDOM Change
1Initial rendercount = 0Render componentcount = 0Counter componentButton shows 'Count: 0'
2User clicks buttoncount = 0setCount(1) calledcount = 1Counter componentButton updates to 'Count: 1'
3User clicks buttoncount = 1setCount(2) calledcount = 2Counter componentButton updates to 'Count: 2'
4User clicks buttoncount = 2setCount(3) calledcount = 3Counter componentButton updates to 'Count: 3'
5No further clickscount = 3No actioncount = 3No re-renderDOM unchanged
💡 Execution stops when no user events trigger state updates.
Variable Tracker
VariableStartAfter 1After 2After 3Final
count01233
Key Moments - 3 Insights
Why does the component re-render after calling setCount?
Calling setCount updates the state, which tells React to re-render the component with the new state value, as shown in steps 2-4 of the execution_table.
Does React update the DOM immediately when setCount is called?
No, React schedules a re-render first, then updates the DOM after rendering completes, as seen between the 'Action' and 'DOM Change' columns in the execution_table.
What happens if setCount is called with the same value as current state?
React will not re-render the component because the state did not change, so the DOM remains unchanged. This is implied in step 5 where no action occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' after step 3?
A3
B2
C1
D0
💡 Hint
Check the 'State After' column in row 3 of the execution_table.
At which step does the DOM update to show 'Count: 1'?
AStep 2
BStep 3
CStep 1
DStep 5
💡 Hint
Look at the 'DOM Change' column for when the button text changes to 'Count: 1'.
If the user never clicks the button, what happens to the state and DOM after initial render?
AState changes, DOM updates
BState stays same, DOM updates
CState stays same, DOM stays same
DState changes, DOM stays same
💡 Hint
Refer to step 5 in the execution_table where no action occurs.
Concept Snapshot
React state updates flow:
- useState creates state and setter
- setState triggers re-render
- Component re-renders with new state
- DOM updates reflect new state
- No re-render if state unchanged
Full Transcript
This visual execution shows how React updates state using useState. Initially, the component renders with count 0. When the user clicks the button, setCount is called with count + 1. React schedules a re-render, then updates the component and DOM to show the new count. This repeats for each click. If no clicks happen, state and DOM stay the same. Key points: setState triggers re-render, DOM updates after render, no re-render if state unchanged.

Practice

(1/5)
1. What is the correct way to update a state variable count using the useState hook in React?
easy
A. Call the setter function like setCount(newValue) to update the state.
B. Directly assign a new value like count = newValue.
C. Use this.setState({ count: newValue }) inside the component.
D. Update the state by returning a new value from the component function.

Solution

  1. Step 1: Understand how useState works

    The useState hook returns a pair: the current state and a function to update it.
  2. Step 2: Use the setter function to update state

    To change the state, you must call the setter function with the new value, e.g., setCount(newValue).
  3. Final Answer:

    Call the setter function like setCount(newValue) to update the state. -> Option A
  4. Quick Check:

    Update state with setter function = A [OK]
Hint: Always use the setter function from useState to update state [OK]
Common Mistakes:
  • Trying to assign state variable directly
  • Using class component syntax in functional components
  • Returning new value instead of calling setter
2. Which of the following is the correct syntax to initialize a state variable name with value "John" using useState?
easy
A. const name = useState('John');
B. const name = useState('John')[0];
C. const [name, setName] = useState('John');
D. const {name, setName} = useState('John');

Solution

  1. Step 1: Recall useState returns an array

    The useState hook returns an array with two elements: the state variable and the setter function.
  2. Step 2: Use array destructuring to get both

    Use array destructuring syntax: const [name, setName] = useState('John'); to get both the value and setter.
  3. Final Answer:

    const [name, setName] = useState('John'); -> Option C
  4. Quick Check:

    useState returns [state, setter] array = B [OK]
Hint: Use array destructuring to get state and setter from useState [OK]
Common Mistakes:
  • Assigning useState result directly without destructuring
  • Using object destructuring instead of array
  • Only taking the first element without setter
3. What will be the output of the following React component when the button is clicked once?
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1);
  };
  return (
    <>
      

{count}

Increment </> ); }
medium
A. 2
B. 0
C. Error
D. 1

Solution

  1. Step 1: Understand state updates are asynchronous and batched

    Both setCount(count + 1) calls use the same count value (0) because state updates are batched.
  2. Step 2: Result after both calls

    Both calls set count to 1, so after clicking, count becomes 1, not 2.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Multiple setState with same value = C [OK]
Hint: Multiple setState calls with same value batch to last one [OK]
Common Mistakes:
  • Assuming count increments twice immediately
  • Expecting count to be 2 after two calls
  • Ignoring React's batching behavior
4. Identify the error in the following React component that tries to update state on button click:
import React, { useState } from 'react';

function Toggle() {
  const [isOn, setIsOn] = useState(false);
  function handleClick() {
    isOn = !isOn;
  }
  return {isOn ? 'ON' : 'OFF'};
}
medium
A. Button missing onClick handler.
B. Directly assigning to state variable instead of using setter.
C. Using incorrect initial state value.
D. Missing parentheses in function declaration.

Solution

  1. Step 1: Check how state is updated

    The code tries to assign isOn = !isOn; directly, which is not allowed for state variables.
  2. Step 2: Correct way to update state

    State must be updated by calling the setter function: setIsOn(!isOn);.
  3. Final Answer:

    Directly assigning to state variable instead of using setter. -> Option B
  4. Quick Check:

    Update state only via setter function = D [OK]
Hint: Never assign state variable directly; always use setter [OK]
Common Mistakes:
  • Assigning state variable directly
  • Forgetting to call setter function
  • Confusing state variable with setter
5. You want to update a state object user with a new age property without losing other properties. Which is the correct way to update state using setUser?
const [user, setUser] = useState({ name: 'Alice', age: 25 });

// Update age to 26
hard
A. setUser(prevUser => ({ ...prevUser, age: 26 }));
B. setUser({ age: 26 });
C. setUser(user.age = 26);
D. setUser(prevUser => { prevUser.age = 26 });

Solution

  1. Step 1: Preserve existing properties when updating state object

    To update one property without losing others, copy previous state using spread syntax.
  2. Step 2: Use functional update form to get latest state

    Use setUser(prevUser => ({ ...prevUser, age: 26 })) to merge old properties with new age.
  3. Final Answer:

    setUser(prevUser => ({ ...prevUser, age: 26 })); -> Option A
  4. Quick Check:

    Use spread and functional update to merge state = A [OK]
Hint: Use spread operator and functional setter to update object state [OK]
Common Mistakes:
  • Replacing whole object losing other properties
  • Mutating state directly instead of returning new object
  • Not using functional update when depending on previous state
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard