Hooks Enable Logic Extraction
What you'll learn: How custom hooks let you pull stateful logic out of components and reuse it without props or HOCs.
The Core Problem Classes Couldn't Solve
Remember the wrapper hell and scattered logic issues from class components? If you wanted to reuse stateful logic (like fetching data or tracking window size), you had two bad options:
- Higher-Order Components (HOCs): Wrap your component in another component, adding nesting and making the tree messy
- Render Props: Pass functions around, creating deeply nested JSX
Both worked, but both cluttered your component hierarchy. You couldn't just "extract the logic" cleanly.
How Hooks Change Everything
Hooks let you extract stateful logic into custom hooks — plain JavaScript functions that use built-in hooks internally. No wrapper components needed. No extra layers in your tree.
Think of it like this: with classes, sharing logic was like borrowing a tool that came attached to a whole toolbox. With hooks, you can just grab the one tool you need.
The Magic: Same Logic, Different Components
A custom hook is just a function starting with use that can call other hooks. You write it once, then call it in any component:
// The extracted logic (you'll learn to write these soon)
function useWindowWidth() {
// Uses useState and useEffect internally
// Returns just the width value
}
// Use it anywhere
function ComponentA() {
const width = useWindowWidth();
// ...
}
function ComponentB() {
const width = useWindowWidth(); // Same logic, no wrappers!
// ...
}
Each component gets its own independent state, but the logic is shared. No props drilling. No extra <div> wrappers. Just clean, reusable functions.
Key Takeaway: Hooks let you extract stateful logic into reusable functions without changing your component hierarchy — solving one of class components' biggest pain points.