⚛️ React Hooks

Chapter 7 of 15

What are Hooks?

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.

💡 History: Hooks were introduced in React 16.8 (February 2019) and revolutionized how we write React components!

Why Hooks?

Before Hooks, you had to use class components to use state and lifecycle methods. Hooks allow you to use these features in function components, which are:

Hooks Rules

There are 3 important rules for using hooks:

  1. Hooks can only be called inside React function components
  2. Hooks can only be called at the top level of a component
  3. Hooks cannot be conditional
⚠️ Invalid Hook Calls:
// ❌ Don't call Hooks inside loops
for (let i = 0; i < 10; i++) {
  const [count, setCount] = useState(0);
}

// ❌ Don't call Hooks inside conditions
if (someCondition) {
  const [count, setCount] = useState(0);
}

// ❌ Don't call Hooks inside nested functions
function handleClick() {
  const [count, setCount] = useState(0);
}

Built-in Hooks

React provides several built-in hooks:

The useState Hook

The useState Hook allows us to track state in a function component.

Import useState

import { useState } from "react";

Initialize useState

import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("red");

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button onClick={() => setColor("blue")}>
        Blue
      </button>
      <button onClick={() => setColor("green")}>
        Green
      </button>
    </>
  );
}

What Does useState Return?

useState returns an array with two values:

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

Multiple State Hooks

You can use multiple useState Hooks in a single 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>
    </>
  );
}

State with Objects

You can use objects with useState to organize related data:

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>
    </>
  );
}
✨ Remember: When updating objects in state, use the spread operator ... to keep all other properties intact!

Toggle Example

A common use case is toggling boolean values:

import { useState } from "react";

function Toggle() {
  const [isOn, setIsOn] = useState(false);

  const toggle = () => {
    setIsOn(prevState => !prevState);
  };

  return (
    <div>
      <p>The light is {isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>
        {isOn ? "Turn OFF" : "Turn ON"}
      </button>
    </div>
  );
}

Counter Example

A classic example demonstrating state updates:

import { useState } from "react";

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

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

Array State Example

Managing lists with useState:

import { useState } from "react";

function ShoppingList() {
  const [items, setItems] = useState(["Milk", "Bread", "Eggs"]);
  const [newItem, setNewItem] = useState("");

  const addItem = () => {
    if (newItem.trim()) {
      setItems([...items, newItem]);
      setNewItem("");
    }
  };

  const removeItem = (index) => {
    setItems(items.filter((_, i) => i !== index));
  };

  return (
    <div>
      <h2>Shopping List</h2>
      <ul>
        {items.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => removeItem(index)}>
              Remove
            </button>
          </li>
        ))}
      </ul>
      <input
        type="text"
        value={newItem}
        onChange={(e) => setNewItem(e.target.value)}
        placeholder="Add new item"
      />
      <button onClick={addItem}>Add</button>
    </div>
  );
}

Lazy Initial State

If the initial state is expensive to compute, you can pass a function:

const [state, setState] = useState(() => {
  const initialState = expensiveComputation();
  return initialState;
});

// This is more efficient than:
const [state, setState] = useState(expensiveComputation());
// Because the function only runs once

Comparing to Class Components

Here's how useState compares to class component state:

Function Component with useState

function Example() {
  const [count, setCount] = useState(0);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

Class Component

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Clicked {this.state.count} times
      </button>
    );
  }
}
✨ Much Cleaner: The function component with useState is much shorter and easier to read!

Common Patterns

Form Handling

function ContactForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: ""
  });

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

  return (
    <form>
      <input name="name" value={formData.name} onChange={handleChange} />
      <input name="email" value={formData.email} onChange={handleChange} />
      <textarea name="message" value={formData.message} onChange={handleChange} />
    </form>
  );
}

Best Practices

What's Next?

Now that you've mastered useState, you're ready to learn about Events - how to handle user interactions in React!