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.
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:
- Simpler and easier to understand
- Less code to write
- Easier to test
- Better for reusing stateful logic
Hooks Rules
There are 3 important rules for using hooks:
- Hooks can only be called inside React function components
- Hooks can only be called at the top level of a component
- Hooks cannot be conditional
// ❌ 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:
- useState - Manage state in function components
- useEffect - Perform side effects
- useContext - Access React Context
- useRef - Reference DOM elements or persist values
- useReducer - Alternative to useState for complex state logic
- useCallback - Memoize functions
- useMemo - Memoize values
- And more!
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:
- Index 0: The current state
- Index 1: A function that updates the state
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>
</>
);
}
... 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>
);
}
}
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
- Keep related state together in an object
- Use multiple state variables for unrelated data
- Use functional updates when new state depends on old state
- Don't call hooks inside conditions, loops, or nested functions
- Always call hooks at the top level of your component
What's Next?
Now that you've mastered useState, you're ready to learn about Events - how to handle user interactions in React!