Bird
Raised Fist0
Reactframework~10 mins

Multiple state variables in React - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Multiple state variables
Component Render
↓
Initialize state variables
↓
Render JSX with state values
↓
User triggers event
↓
Call setState for one variable
↓
React schedules re-render
↓
Component re-renders with updated state
↓
Repeat on further events or exit
The component initializes multiple state variables separately, updates them independently on events, and re-renders reflecting the latest values.
Execution Sample
React
import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  return (
    <div>...</div>
  );
}
This React component uses two separate state variables: count and name, each with its own setter.
Execution Table
StepActioncountnameRendered Output
1Initial render0''Count: 0, Name: ''
2User clicks increment buttonsetCount(1)''Count: 0, Name: '' (before re-render)
3React re-renders with count=11''Count: 1, Name: ''
4User types 'A' in input1setName('A')Count: 1, Name: '' (before re-render)
5React re-renders with name='A'1'A'Count: 1, Name: 'A'
6User clicks increment button againsetCount(2)'A'Count: 1, Name: 'A' (before re-render)
7React re-renders with count=22'A'Count: 2, Name: 'A'
8User types 'AB' in input2setName('AB')Count: 2, Name: 'A' (before re-render)
9React re-renders with name='AB'2'AB'Count: 2, Name: 'AB'
10No more events2'AB'Count: 2, Name: 'AB'
💡 No more user events; component state remains stable.
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 9Final
count011222
name'''''A''A''AB''AB'
Key Moments - 2 Insights
Why does updating one state variable not reset the other?
Because React state variables are independent; updating count with setCount does not affect name, as shown in steps 2-3 and 4-5 where only one variable changes.
Why does the rendered output show old state values before re-render?
React batches state updates and re-renders asynchronously; after calling setState, the UI shows previous values until React re-renders, as seen in steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 5. What is the value of 'name' after React re-renders?
A''
B'A'
C'AB'
Dundefined
💡 Hint
Check the 'name' column at step 5 in the execution_table.
At which step does 'count' first update to 2?
AStep 7
BStep 3
CStep 5
DStep 9
💡 Hint
Look at the 'count' column in execution_table rows to find when it becomes 2.
If the user types 'ABC' instead of 'AB', how would the variable_tracker change?
ABoth 'count' and 'name' would reset to initial values.
BThe 'count' variable would also change to 3.
CThe final 'name' value would be 'ABC' instead of 'AB'.
DNo change in variable_tracker.
💡 Hint
Consider how typing affects only the 'name' state variable as shown in variable_tracker.
Concept Snapshot
Multiple state variables in React:
- Use separate useState calls for each variable.
- Each state updates independently.
- setState triggers re-render with updated value.
- Previous state variables remain unchanged.
- UI updates after React re-renders.
Full Transcript
This example shows a React component with two state variables: count and name. Initially, count is 0 and name is empty. When the user clicks a button, setCount updates count, triggering a re-render that shows the new count but leaves name unchanged. When the user types in an input, setName updates name, triggering a re-render that updates the displayed name but leaves count unchanged. Each state variable is independent, and React batches updates before re-rendering. The execution table traces each step, showing state before and after updates and the rendered output. The variable tracker summarizes how count and name change over time. Key moments clarify why updating one state does not affect the other and why UI updates happen after re-render. The quiz tests understanding of state values at specific steps and how changes affect the component.

Practice

(1/5)
1. In React, why would you use multiple state variables instead of one single state object?
easy
A. To keep different pieces of data separate and update them independently.
B. Because React only allows one state variable per component.
C. To make the component slower and harder to read.
D. To avoid using setter functions.

Solution

  1. Step 1: Understand state separation

    Multiple state variables let you store different data separately, making updates easier and clearer.
  2. Step 2: Recognize React's flexibility

    React allows many state variables, each with its own setter, improving organization and readability.
  3. Final Answer:

    To keep different pieces of data separate and update them independently. -> Option A
  4. Quick Check:

    Separate state variables = easier updates [OK]
Hint: Multiple states mean clearer, independent updates [OK]
Common Mistakes:
  • Thinking React limits to one state variable
  • Believing multiple states slow down components
  • Confusing state variables with props
2. Which of the following is the correct way to declare two separate state variables in a React functional component?
easy
A. const [count, setCount] = useState(0); const [name, setName] = useState('');
B. const state = useState({count: 0, name: ''});
C. const count = useState(0); const name = useState('');
D. useState(count, 0); useState(name, '');

Solution

  1. Step 1: Check syntax for multiple states

    Each state variable uses its own useState call with array destructuring for value and setter.
  2. Step 2: Compare options

    const [count, setCount] = useState(0); const [name, setName] = useState(''); correctly declares two separate states with their setters. Others misuse useState or syntax.
  3. Final Answer:

    const [count, setCount] = useState(0); const [name, setName] = useState(''); -> Option A
  4. Quick Check:

    Separate useState calls = correct syntax [OK]
Hint: Use separate useState calls with array destructuring [OK]
Common Mistakes:
  • Trying to declare multiple states in one useState call without destructuring
  • Missing setter functions
  • Incorrect useState syntax
3. What will be the output of this React component when the button is clicked once?
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('Hello');

  function handleClick() {
    setCount(count + 1);
    setText(text + '!');
  }

  return (
    <div>
      <p>Count: {count}</p>
      <p>Text: {text}</p>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}
medium
A. Count: 0 and Text: Hello
B. Count: 0 and Text: Hello!
C. Count: 1 and Text: Hello!
D. Count: 1 and Text: Hello

Solution

  1. Step 1: Understand state updates on click

    Clicking the button calls handleClick, which increments count by 1 and adds '!' to text.
  2. Step 2: Check initial values and updates

    Initial count is 0, text is 'Hello'. After one click, count becomes 1, text becomes 'Hello!'.
  3. Final Answer:

    Count: 1 and Text: Hello! -> Option C
  4. Quick Check:

    State updates reflect in UI after click [OK]
Hint: Each setter updates its own state independently [OK]
Common Mistakes:
  • Assuming states update asynchronously and show old values immediately
  • Forgetting to update both states
  • Mixing up initial and updated values
4. Identify the error in this React component using multiple state variables:
import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  function update() {
    setCount(count + 1);
    setName = 'John';
  }

  return <button onClick={update}>Update</button>;
}
medium
A. Missing import of useState from React.
B. Not initializing count with a string.
C. Using semicolon after return statement.
D. Incorrect assignment to setName instead of calling it as a function.

Solution

  1. Step 1: Check how state setters are used

    State setters like setName must be called as functions, e.g., setName('John').
  2. Step 2: Identify the error in update function

    The code uses assignment setName = 'John' instead of calling setName('John'), which is incorrect.
  3. Final Answer:

    Incorrect assignment to setName instead of calling it as a function. -> Option D
  4. Quick Check:

    State setters must be called, not assigned [OK]
Hint: Call setters as functions, never assign them [OK]
Common Mistakes:
  • Assigning value to setter instead of calling it
  • Forgetting to import useState
  • Misusing return syntax
5. You want to track a user's first name, last name, and age separately in a React component. Which approach best uses multiple state variables to keep the component organized and easy to update?
hard
A. Use one useState call with an object containing first name, last name, and age.
B. Use three separate useState calls: one for first name, one for last name, and one for age.
C. Use one useState call with an array containing first name, last name, and age.
D. Use three variables without useState since they don't change.

Solution

  1. Step 1: Consider state clarity and updates

    Using separate state variables for each piece of data allows independent updates and clearer code.
  2. Step 2: Compare with other options

    Use one useState call with an object containing first name, last name, and age. groups data but requires careful merging on updates. Use one useState call with an array containing first name, last name, and age. uses array which is less clear. Use three variables without useState since they don't change. ignores state management.
  3. Final Answer:

    Use three separate useState calls: one for first name, one for last name, and one for age. -> Option B
  4. Quick Check:

    Separate states = easier updates and clarity [OK]
Hint: Separate states for separate data pieces [OK]
Common Mistakes:
  • Using one object state and forgetting to merge updates
  • Using arrays for unrelated data
  • Not using state for changing data
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