Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

Managing Multiple States in a Component

Recommended resources

Introduction

Hello! In our previous lesson, we mastered the functional update form, setState(prevState => ...), which is crucial for reliably updating state based on its previous values. We saw how it prevents "stale state" bugs and elegantly handles updates inside closures.

So far, we've mostly worked with components that manage one or two state variables. However, real-world components often need to "remember" many different pieces of information. This leads to a key architectural question: how should we structure that state?

In this lesson, we will focus on exactly that. Our goal is to learn how to manage multiple independent pieces of state in a single component. We will explore two primary strategies:

  1. Using multiple useState calls for each piece of state.
  2. Grouping related state into a single object within one useState call.

We'll analyze the trade-offs of each approach and establish clear guidelines for when to use them, all while ensuring our state is fully type-safe with TypeScript.


The Standard Approach: Multiple useState Hooks

The most common and generally recommended approach is to declare a separate useState hook for each independent piece of state.

A piece of state is "independent" if it doesn't necessarily need to change when another piece of state changes. For example, in a form, the user's name and their agreement to the terms of service are independent.

Let's look at a component with two unrelated state variables: a numeric counter and a boolean flag to toggle visibility.

import { useState } from 'react';

function MyComponent() {
  // State for the counter
  const [count, setCount] = useState<number>(0);
  
  // State for the visibility toggle
  const [isVisible, setIsVisible] = useState<boolean>(true);

  const handleIncrement = () => {
    // Updating 'count' doesn't affect 'isVisible'
    setCount(c => c + 1); 
  };

  const handleToggleVisibility = () => {
    // Updating 'isVisible' doesn't affect 'count'
    setIsVisible(v => !v);
  };

  return (
    <div>
      <button onClick={handleIncrement}>Count is {count}</button>
      <hr />
      <button onClick={handleToggleVisibility}>
        {isVisible ? 'Hide' : 'Show'} Details
      </button>
      {isVisible && <p>Here are the secret details!</p>}
    </div>
  );
}

This approach has several advantages:

  • Readability: State variables like count and isVisible have clear, descriptive names.
  • Simplicity of Updates: State setters like setCount and setIsVisible are straightforward. You don't need to worry about accidentally affecting other state variables.
  • Reusability: It's easier to extract logic related to a single piece of state into a custom hook (a topic we'll cover later).

The official React documentation provides an excellent example of this pattern.

Giving a component multiple state variables

Please read the following section from the React documentation, 'State: A Component's Memory'. It demonstrates this exact concept with a gallery component that manages a numeric index and a boolean showMore as separate state variables.

Focus on the section titled 'Giving a component multiple state variables'. Observe how useState is called twice to create index and showMore, and how their respective event handlers update them independently.


The Alternative: Grouping Related State in an Object

While multiple useState calls are the default, there are situations where it makes sense to group related data into a single state object. This is generally advisable when:

  • Multiple state variables will almost always be updated at the same time.
  • The state represents a single, cohesive concept, like the coordinates of a point ({x, y}).

Let's imagine a form for a user profile. The firstName and lastName fields are closely related. We can choose to group them.

First, we define an interface for our state's shape, which is a best practice in TypeScript.

interface Profile {
  firstName: string;
  lastName: string;
}

Then, we use it to initialize our state:

const [profile, setProfile] = useState<Profile>({
  firstName: 'Satoshi',
  lastName: 'Nakamoto',
});

The Critical Rule: Immutable Updates

Here comes the most important part. When you use an object for state, the useState setter function replaces the entire object. It does not automatically merge the old and new state.

If you only provide the field you're changing, you will lose all the other data in the object.

// WRONG: This will delete the lastName property!
const handleFirstNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  setProfile({ firstName: e.target.value }); 
};

To update the object correctly, you must create a new object, copy over all the properties from the previous state, and then overwrite the specific property you want to change. The spread syntax (...) is perfect for this.

// CORRECT: Spreading the previous state preserves other properties
const handleFirstNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  setProfile(prevProfile => ({
    ...prevProfile,
    firstName: e.target.value,
  }));
};

Learn useState In 15 Minutes - React Hooks Explained

The following video provides a powerful visual demonstration of this exact pitfall. The presenter initially forgets to spread the previous state, causing part of the UI to disappear.

Watch from 11:12 to 13:53. Notice how the 'theme' value vanishes when the count is updated without spreading the previousState object. This highlights why immutable updates are non-negotiable when using state objects.


Deciding Which Approach to Use

So, when should you use multiple useState calls versus a single state object? Here's a guiding principle:

Prefer multiple useState calls if the state variables are unrelated.

The React team themselves offer this advice. If changing one variable doesn't imply the other should also change, keep them separate. This reduces the complexity of your update logic, as you don't have to constantly remember to spread previous state.

State: A Component's Memory

The React documentation offers a concise guideline on this topic.

Read the short paragraph right below the first code example in the section 'Giving a component multiple state variables'. It starts with 'It is a good idea to have multiple state variables if their state is unrelated...'. This is the key heuristic to remember.

The video you just watched concludes with the same recommendation, refactoring the object-based state into two separate, simpler useState calls.

Learn useState In 15 Minutes - React Hooks Explained

Now, watch the next segment of the same video, where the presenter fixes the object complexity by switching to the multiple-hook pattern.

Watch from 13:43 to 15:25. This part directly contrasts the two approaches and concludes that using multiple useState hooks is often cleaner and easier to manage.

Test your understanding!

You are building a settings panel component for a text editor. It needs to manage the following pieces of state:

  • Font size (e.g., 14)
  • Font family (e.g., 'Fira Code')
  • Theme (e.g., 'dark')
  • Whether word wrap is enabled (a boolean)

How would you structure the state for this component using useState and TypeScript? Write out the state declarations.

Show answer

The best approach is to use multiple useState calls because these settings are largely independent. A user can change the font size without affecting the theme or word wrap setting.

import { useState } from 'react';

function EditorSettings() {
  const [fontSize, setFontSize] = useState<number>(14);
  const [fontFamily, setFontFamily] = useState<string>('Fira Code');
  const [theme, setTheme] = useState<'dark' | 'light'>('dark');
  const [wordWrapEnabled, setWordWrapEnabled] = useState<boolean>(true);

  // ... component logic ...
}

Grouping these into a single object would require you to spread the entire settings object for every small change, adding unnecessary boilerplate and risk of error.


State is Isolated and Private

A final, crucial concept to cement your understanding is that state is completely local to a component instance. If you render the same component multiple times on a page, each one gets its own independent copy of its state. Changing the state of one will not affect the others.

For example, if we render our MyComponent from earlier twice:

function App() {
  return (
    <>
      <h2>First Counter</h2>
      <MyComponent />
      <hr />
      <h2>Second Counter</h2>
      <MyComponent />
    </>
  );
}

Clicking the buttons in the "First Counter" section will only update its own count and isVisible state. The "Second Counter" will remain completely unaffected. This is a fundamental aspect of what makes React components modular and reusable.

State is isolated and private

The React documentation explains this concept of isolated state very clearly.

Read the section titled 'State is isolated and private'. The example with two Gallery components is a perfect illustration of this principle.


Conclusion

You've now learned how to structure state within a React component. This is a core architectural decision you'll make every time you build a new component.

Key Takeaways:

  • Multiple useState is the default: For unrelated pieces of state, use separate useState hooks. This leads to cleaner, more readable code and simpler update logic.
  • Group state in objects for related data: Only group state variables into a single object if they are tightly coupled and often change together (e.g., form fields, coordinates).
  • Immutability is key for objects: When updating a state object, you must create a new object by spreading the properties of the previous state ({...prevState, ...}) to avoid data loss.
  • State is private to each instance: Every instance of a component on the screen maintains its own independent set of state variables.

Next Steps

We've touched upon the mechanics of updating objects in state, but this topic is so critical that it deserves its own dedicated lesson. In our next session, we will do a deep dive to work with object and array state, ensuring immutable updates. We'll cover common patterns, helper functions, and how to avoid subtle bugs when dealing with complex nested data structures.