Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟢 Beginner🔵 Advanced
💾 Introduction to State⚛️ Using useState Hook🔄 Updating State Correctly🎯 Initial State Values🚫 Common State Mistakes📊 Multiple State Variables🔗 State & Rendering📝 Forms with State🏗️ State Structure Best Practices
Reactjs/State/Multiple State Variables

📌 Working with Multiple State Variables — Managing Complexity

Components often need multiple state variables to track different pieces of data. Use separate `useState` hooks for each piece of state.


🎯 Multiple useState Calls

Call `useState` multiple times in the same component. Each call creates a separate state variable that can be updated independently.

Each `useState` call creates one state variable. You can have as many as you need in a single component. They're completely independent of each other.

import { useState } from 'react';

function UserProfile() {
  const [name, setName] = useState('John');
  const [age, setAge] = useState(30);
  const [email, setEmail] = useState('john@example.com');

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Email: {email}</p>
      <button onClick={() => setName('Jane')}>Change Name</button>
      <button onClick={() => setAge(age + 1)}>Increase Age</button>
    </div>
  );
}

<details>

<summary>📚 More Examples</summary>

// Example: Form with multiple inputs

function ContactForm() {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log({ firstName, lastName, phone, message });
    // Reset form
    setFirstName('');
    setLastName('');
    setPhone('');
    setMessage('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={firstName}
        onChange={(e) => setFirstName(e.target.value)}
        placeholder="First Name"
      />
      <input
        value={lastName}
        onChange={(e) => setLastName(e.target.value)}
        placeholder="Last Name"
      />
      <input
        value={phone}
        onChange={(e) => setPhone(e.target.value)}
        placeholder="Phone"
      />
      <textarea
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        placeholder="Message"
      />
      <button type="submit">Send</button>
    </form>
  );
}

</details>

💡 Independent State Variables

Each state variable is independent. Updating one doesn't affect the others. This makes components easier to understand and test.

import { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);

  return (
    <div>
      <input
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <label>
        <input
          type="checkbox"
          checked={rememberMe}
          onChange={(e) => setRememberMe(e.target.checked)}
        />
        Remember me
      </label>
      <button onClick={() => console.log({ email, password, rememberMe })}>
        Login
      </button>
    </div>
  );
}

<details>

<summary>📚 More Examples</summary>

// Example: Toggle multiple UI states

function Dashboard() {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [darkMode, setDarkMode] = useState(false);
  const [notifications, setNotifications] = useState(3);

  return (
    <div style={{ background: darkMode ? '#333' : '#fff' }}>
      <button onClick={() => setSidebarOpen(!sidebarOpen)}>
        Toggle Sidebar
      </button>
      <button onClick={() => setDarkMode(!darkMode)}>
        Toggle Dark Mode
      </button>
      <p>Notifications: {notifications}</p>
      <button onClick={() => setNotifications(0)}>Clear</button>
    </div>
  );
}

</details>

🔧 Organizing State

Put related state together. If some state variables are always updated together, consider grouping them into an object.

import { useState } from 'react';

// ❌ Too many separate variables
function BadComponent() {
  const [street, setStreet] = useState('');
  const [city, setCity] = useState('');
  const [state, setState] = useState('');
  const [zip, setZip] = useState('');
  // Gets messy with many related values
}

// ✅ Group related state
function GoodComponent() {
  const [address, setAddress] = useState({
    street: '',
    city: '',
    state: '',
    zip: '',
  });

  const updateAddress = (field, value) => {
    setAddress({ ...address, [field]: value });
  };

  return (
    <div>
      <input
        value={address.street}
        onChange={(e) => updateAddress('street', e.target.value)}
        placeholder="Street"
      />
      <input
        value={address.city}
        onChange={(e) => updateAddress('city', e.target.value)}
        placeholder="City"
      />
    </div>
  );
}

📊 Summary

ConceptDescription
Independent stateEach useState is separate
Multiple hooksCall useState as many times as needed
Grouping stateUse objects for related values
UpdatesEach setter can be called independently

🔑 Key Takeaways

  • ✅ Call `useState` multiple times for multiple state variables
  • ✅ Each state variable is completely independent
  • ✅ Update one state without affecting others
  • ✅ Group related state into objects to reduce variables
  • ✅ Each component instance gets its own separate copy of state
  • ✅ More state variables = more complex components (consider refactoring)

Ready to practice? Challenges | Next: State Best Practices


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn