Part 3: Mastering State and Events in React

Welcome to Part 3 of our React.js series! Today we’ll unlock the power of state management and event handling – the core of interactive React applications.

Understanding State in React

State allows components to “remember” information and re-render when that information changes.

The useState Hook

import { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Key Concepts:

  • useState returns an array with [currentValue, setterFunction]
  • Always call hooks at the top level of your component
  • State updates trigger re-renders

Handling Events in React

Basic Event Handling

function ButtonClicker() {
  const handleClick = () => {
    alert('Button was clicked!');
  };

  return <button onClick={handleClick}>Click Me</button>;
}

Passing Arguments to Event Handlers

function TodoList() {
  const todos = ['Buy milk', 'Walk dog', 'Write React code'];
  
  const handleDelete = (index) => {
    alert(`Deleting item ${index}`);
  };

  return (
    <ul>
      {todos.map((todo, index) => (
        <li key={index}>
          {todo}
          <button onClick={() => handleDelete(index)}>
            Delete
          </button>
        </li>
      ))}
    </ul>
  );
}

Forms and Controlled Components

function SignupForm() {
  const [formData, setFormData] = useState({
    email: '',
    password: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Submitted: ${formData.email}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
      />
      <button type="submit">Sign Up</button>
    </form>
  );
}

Key Form Concepts:

  • Controlled components tie form elements to state
  • Use e.preventDefault() to prevent page reloads
  • The name attribute should match your state keys

Practical Example: Shopping Cart

function ShoppingCart() {
  const [items, setItems] = useState([
    { id: 1, name: 'Laptop', quantity: 1 },
    { id: 2, name: 'Mouse', quantity: 2 }
  ]);

  const updateQuantity = (id, newQuantity) => {
    setItems(items.map(item =>
      item.id === id ? { ...item, quantity: newQuantity } : item
    ));
  };

  const removeItem = (id) => {
    setItems(items.filter(item => item.id !== id));
  };

  return (
    <div className="cart">
      <h2>Your Cart</h2>
      {items.length === 0 ? (
        <p>Your cart is empty</p>
      ) : (
        <ul>
          {items.map(item => (
            <li key={item.id}>
              {item.name} - Qty: {item.quantity}
              <button onClick={() => updateQuantity(item.id, item.quantity + 1)}>
                +
              </button>
              <button onClick={() => removeItem(item.id)}>
                Remove
              </button>
            </li>
          ))}
        </ul>
      )}
      <p>Total Items: {items.reduce((sum, item) => sum + item.quantity, 0)}</p>
    </div>
  );
}

What’s Next?

In Part 4, we’ll explore:
✅ useEffect for side effects
✅ Conditional rendering patterns
✅ React hooks deep dive

Exercise for You

Create a ThemeSwitcher component with a button that toggles between light/dark mode using state. Store the current theme in state and apply different CSS classes based on the theme.


Enjoyed this tutorial? Subscribe for Part 4! 💡

Questions? Ask in the comments below!


Series Navigation:

🔹 Part 1: Introduction to React
🔹 Part 2: JSX, Components & Props
🔹 Part 3: State and Events (You’re here)
🔹 Part 4: useEffect and Conditional Rendering

Leave a Comment

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