Bird
Raised Fist0
Reactframework~30 mins

Multiple state variables in React - Mini Project: Build & Apply

Choose your learning style10 modes available
Managing Multiple State Variables in React
📖 Scenario: You are building a simple user profile form in React. The form will collect a user's first name and last name. You want to store these two pieces of information separately in the component's state.
🎯 Goal: Create a React functional component that uses two separate state variables to hold the firstName and lastName. Then display the full name by combining these two states.
📋 What You'll Learn
Use React functional component syntax
Use useState hook twice to create two state variables: firstName and lastName
Initialize firstName with the string "John"
Initialize lastName with the string "Doe"
Render a <div> that shows the full name by combining firstName and lastName with a space in between
💡 Why This Matters
🌍 Real World
Managing multiple pieces of user input separately is common in forms, profile pages, and settings in web apps.
💼 Career
Understanding how to handle multiple state variables and controlled inputs is essential for React developers building interactive user interfaces.
Progress0 / 4 steps
1
Set up the React component and initial state variables
Create a React functional component called UserProfile. Inside it, use the useState hook to create a state variable called firstName and initialize it with the string "John". Also create a state variable called lastName and initialize it with the string "Doe". Import useState from react.
React
Hint

Remember to import useState from react. Use const [state, setState] = useState(initialValue) syntax.

2
Add JSX to display the full name
Inside the UserProfile component, return a <div> element that displays the full name by combining the firstName and lastName state variables separated by a space.
React
Hint

Use JSX syntax to return a <div> with curly braces to insert the state variables.

3
Add input fields to update the first and last names
Add two <input> fields inside the returned JSX. The first input should have its value set to firstName and update firstName using setFirstName on change. The second input should have its value set to lastName and update lastName using setLastName on change.
React
Hint

Use controlled inputs by setting value and onChange handlers that update the state.

4
Add accessibility labels and wrap inputs in a form
Wrap the two input fields inside a <form> element. Add aria-label attributes to the inputs: aria-label="First Name" for the first input and aria-label="Last Name" for the second input to improve accessibility.
React
Hint

Use a <form> tag to group inputs and add aria-label attributes for screen readers.

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