Introduction to React Hooks
1/5/2025
Introduction to React Hooks
Hooks are functions that let you “hook into” React state and lifecycle features from function components.
Why Hooks?
- Reuse stateful logic between components
- Split complex components into smaller functions
- Use React features without classes
Rules of Hooks
- Only call Hooks at the top level
- Only call Hooks from React functions
useState
The most basic Hook for managing state:
jsx
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
)
}Multiple State Variables
jsx
function Form() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [age, setAge] = useState(0)
// ...
}State with Objects
jsx
const [user, setUser] = useState({ name: '', email: '' })
// Update correctly by spreading
setUser({ ...user, name: 'John' })
Monkey Knows Wiki