React Lesson 6: State with useState

⚛️ React CourseLesson 6 of 15 · 40% complete

State is data that belongs to a component and can change over time. When state changes, React automatically re-renders the component. This is the magic of React.

useState Hook

import { useState } from "react";

function Counter() {
  // [currentValue, functionToUpdate]
  const [count, setCount] = useState(0);  // 0 is initial value
  
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

State with Strings and Booleans

function ToggleButton() {
  const [isOn, setIsOn] = useState(false);
  
  return (
    <button
      onClick={() => setIsOn(!isOn)}
      style={{ background: isOn ? "green" : "gray" }}
    >
      {isOn ? "ON" : "OFF"}
    </button>
  );
}

function TextInput() {
  const [text, setText] = useState("");
  
  return (
    <div>
      <input
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type here..."
      />
      <p>You typed: {text}</p>
      <p>Characters: {text.length}</p>
    </div>
  );
}

State with Objects

function UserProfile() {
  const [user, setUser] = useState({
    name: "Alice",
    age: 30,
    email: "alice@example.com"
  });
  
  const updateAge = () => {
    // Always spread to keep other properties!
    setUser({ ...user, age: user.age + 1 });
  };
  
  return (
    <div>
      <p>{user.name} — Age: {user.age}</p>
      <button onClick={updateAge}>Birthday!</button>
    </div>
  );
}

🏋️ Practice Task

Build a shopping cart counter. Show the item count (starts at 0). Have “Add Item” and “Remove Item” buttons. Show a message “Cart is empty” when count is 0. Show “🛒 X items in cart” when count > 0. Prevent count from going below 0.

💡 Hint: Use useState(0). In remove handler: setCount(prev => Math.max(0, prev – 1)) to prevent negative.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *