Hooks let you "hook into" React features like state and side effects from function components. They're the modern way to build React apps.
useState is like a whiteboard in your room. You write something on it (initial value), and whenever you erase and write something new (call the setter), everyone looking at the whiteboard (the component) sees the update immediately. React re-renders the component every time the whiteboard changes.
useState is the most fundamental hook. It lets a component remember values between renders:
...). Direct mutation won't trigger a re-render, so your UI won't update.
useEffect is like setting an alarm clock. You tell it: "after the component appears on screen (or after something changes), DO THIS." It's for side effects — things that happen OUTSIDE of rendering, like fetching data, starting timers, or updating the document title.
| Dependency Array | When Effect Runs | Analogy |
|---|---|---|
useEffect(fn) — no array | After EVERY render | Alarm that rings every minute |
useEffect(fn, []) — empty array | Only once (on mount) | Alarm that rings once when you wake up |
useEffect(fn, [a, b]) — with values | When a or b changes | Alarm that rings when specific things change |
useRef is like a sticky note attached to your desk. You can write something on it and it stays there between renders, but changing it does NOT cause a re-render (unlike state). It's also used to directly grab DOM elements, like sticking a name tag on a specific HTML element so you can find it later.
| Feature | useState | useRef |
|---|---|---|
| Triggers re-render? | Yes | No |
| Persists between renders? | Yes | Yes |
| Access via | Variable directly | .current property |
| Analogy | Whiteboard (everyone sees changes) | Sticky note (private, no announcement) |
| Use for | Data that affects UI | DOM access, timers, counters that don't affect UI |
useContext, grandpa puts the message on a family bulletin board and anyone in the family can read it directly — no passing needed!
Context solves the "prop drilling" problem — passing props through many layers of components:
use.
| Hook Name | What It Does |
|---|---|
useFetch(url) | Fetches data and returns { data, loading, error } |
useLocalStorage(key) | Syncs state with localStorage |
useDebounce(value, delay) | Delays updating a value (great for search) |
useWindowSize() | Tracks browser window dimensions |
useAuth() | Manages user authentication state |
1. When does useEffect(() => {}, []) run?
2. What's the key difference between useRef and useState?
3. What problem does useContext solve?
4. Which of these is NOT allowed with hooks?
5. What must a custom hook's name start with?