CodeMasteryLab
Section 3

State and Lifecycle

Master React state management and component lifecycle

State and Lifecycle

What is State?

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

useState Hook

The useState hook lets you add state to function components:

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

Multiple State Variables

You can use multiple useState hooks:

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

  // Handle form submission
}

State Updates are Asynchronous

State updates may be batched for performance:

// ❌ Wrong
setCount(count + 1);
setCount(count + 1); // Still adds 1, not 2

// ✅ Correct
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1); // Adds 2

Objects and Arrays in State

When updating objects or arrays, create new copies:

// For objects
setUser({ ...user, name: 'New Name' });

// For arrays
setItems([...items, newItem]);

useEffect Hook

useEffect lets you perform side effects:

import { useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(setData);
  }, []); // Empty array = run once

  return <div>{data?.title}</div>;
}

Cleanup Functions

Return a cleanup function to prevent memory leaks:

useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => clearInterval(timer);
}, []);