⚛️ React State

Chapter 6 of 15

What is State?

React components have a built-in state object. The state object is where you store property values that belong to the component. When the state object changes, the component re-renders.

💡 Props vs State: Props are passed from parent to child and are read-only. State is managed within the component and can be changed!

State in Function Components

To use state in a function component, we use the useState Hook:

import { useState } from "react";

function Car() {
  const [brand, setBrand] = useState("Ford");

  return (
    <div>
      <h1>My {brand}</h1>
      <button onClick={() => setBrand("Volvo")}>
        Change Brand
      </button>
    </div>
  );
}
✨ What Happens: When you click the button, the brand changes from "Ford" to "Volvo", and React automatically re-renders the component!

Understanding useState

The useState Hook returns two values:

const [state, setState] = useState(initialValue);

Reading State

You can use the state variable directly in your JSX:

function Counter() {
  const [count, setCount] = useState(0);

  return <h1>Count: {count}</h1>;
}

Updating State

To update state, call the setter function with the new value:

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

Multiple State Variables

You can use the useState Hook multiple times in one component:

import { useState } from "react";

function Car() {
  const [brand, setBrand] = useState("Ford");
  const [model, setModel] = useState("Mustang");
  const [year, setYear] = useState("1964");
  const [color, setColor] = useState("red");

  return (
    <>
      <h1>My {brand}</h1>
      <p>
        It is a {color} {model} from {year}.
      </p>
    </>
  );
}

Using Objects in State

You can also store objects in state:

import { useState } from "react";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
    </>
  );
}

Updating Objects in State

When updating state with objects, you need to use the spread operator to preserve other properties:

import { useState } from "react";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" };
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>It is a {car.color} {car.model} from {car.year}.</p>
      <button onClick={updateColor}>Blue</button>
    </>
  );
}
⚠️ Important: When updating state, React replaces the old state with the new state. Without the spread operator ..., you would lose all other properties!

Using Arrays in State

You can store arrays in state and update them:

function TodoList() {
  const [todos, setTodos] = useState(["Task 1", "Task 2"]);

  const addTodo = () => {
    setTodos([...todos, "New Task"]);
  };

  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
}

State in Class Components

Before Hooks, we used class components for state. Here's how it works:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }

  changeColor = () => {
    this.setState({ color: "blue" });
  }

  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color} {this.state.model} 
          from {this.state.year}.
        </p>
        <button onClick={this.changeColor}>
          Change color
        </button>
      </div>
    );
  }
}
📚 Note: Modern React apps use function components with Hooks instead of class components. Class components are still supported but not recommended for new code.

Functional Updates

When updating state based on the previous state, use a function:

function Counter() {
  const [count, setCount] = useState(0);

  const incrementTwice = () => {
    // ❌ Wrong - only increments once
    setCount(count + 1);
    setCount(count + 1);

    // ✅ Correct - increments twice
    setCount(prevCount => prevCount + 1);
    setCount(prevCount => prevCount + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementTwice}>+2</button>
    </div>
  );
}

Real-World Example

Here's a practical example of a form with state:

function LoginForm() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (username && password) {
      setIsLoggedIn(true);
    }
  };

  if (isLoggedIn) {
    return <h1>Welcome, {username}!</h1>;
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Login</button>
    </form>
  );
}

State Best Practices

⚠️ Common Mistake:
// ❌ Never do this!
count = 5;  // Wrong! This doesn't trigger re-render

// ✅ Always do this:
setCount(5);  // Correct! This triggers re-render

What's Next?

Now that you understand state, you're ready to dive deeper into React Hooks, starting with a comprehensive look at the useState Hook!