MODULE 5

State & Events

Make your components interactive with state and event handling

Understanding State

State is data that changes over time. When state changes, React re-renders the component to reflect the new data.

Props vs State

State Examples

useState Hook

The useState hook is the primary way to add state to functional components.

Basic Syntax

import { useState } from 'react';

function Counter() {
  // Declare state variable
  const [count, setCount] = useState(0);
  
  // count = current value
  // setCount = function to update value
  // 0 = initial value
  
  return (
    

Count: {count}

); }

Multiple State Variables

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [age, setAge] = useState(0);
  
  return (
    

Name: {name}

Email: {email}

Age: {age}

); }

Complex State (Objects)

function UserProfile() {
  const [user, setUser] = useState({
    name: 'Alice',
    email: 'alice@example.com',
    age: 25
  });
  
  // Update entire object
  const updateUser = (newUser) => {
    setUser(newUser);
  };
  
  // Update one property (immutably)
  const updateName = (newName) => {
    setUser({ ...user, name: newName });
  };
  
  return (
    

{user.name} ({user.email})

); }
💡 Remember: Always treat state as immutable. Create a new object instead of modifying the existing one.

Event Handling

React events are similar to HTML events but with camelCase names.

Common Events

// Click


// Change


// Submit
// Mouse
// Keyboard // Focus

Event Handlers

// Arrow function (preferred)
function Button() {
  const handleClick = () => {
    console.log('Clicked!');
  };
  
  return ;
}

// Inline arrow function
function Button() {
  return ;
}

// Passing arguments
function Button() {
  const handleClick = (id) => {
    console.log('Clicked item:', id);
  };
  
  return ;
}

Access Event Object

function Form() {
  const handleChange = (e) => {
    console.log(e.target.value);  // Get input value
    console.log(e.target.type);   // Get input type
    console.log(e.key);           // For keyboard events
  };
  
  return ;
}

Controlled Inputs

Controlled inputs are connected to state. React controls the input value.

Controlled Input Example

function SearchBox() {
  const [searchTerm, setSearchTerm] = useState('');
  
  return (
    
setSearchTerm(e.target.value)} placeholder="Search..." />

Searching for: {searchTerm}

); }

Why Controlled Inputs Matter

Forms

Handling Form Submission

function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  
  const handleSubmit = (e) => {
    e.preventDefault();  // Prevent page reload
    console.log('Logging in as:', username);
    // Send to server, etc.
  };
  
  return (
    
       setUsername(e.target.value)}
        placeholder="Username"
      />
       setPassword(e.target.value)}
        placeholder="Password"
      />
      
    
  );
}

Multiple Form Fields

function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value  // Update specific field
    });
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
  };
  
  return (