Understanding React Hooks
React Hooks revolutionized how we write components. They let you use state and other React features without writing a class — making code cleaner, more reusable, and easier to test.
The two most-used hooks
useState
Manage local state in a function component:
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
useEffect
Handle side effects like data fetching, subscriptions, or DOM manipulation:
import { useState, useEffect } from 'react'
function UserProfile({ userId }) {
const [user, setUser] = useState(null)
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(setUser)
}, [userId]) // re-run when userId changes
if (!user) return <p>Loading...</p>
return <h1>{user.name}</h1>
}
Beyond the basics
useContext— avoid prop drilling with shared stateuseRef— persist values across renders without re-renderinguseMemo/useCallback— optimize expensive computations and callbacks- Custom Hooks — extract and reuse stateful logic across components
Rules of Hooks
- Only call hooks at the top level (not inside loops, conditions, or nested functions)
- Only call hooks from React function components or custom hooks
Hooks changed the game. If you haven't embraced them yet, now's the time.