Why Are Your Components " Fat " ?
When you're just starting, your components look like Swiss army knives: they load data, validate forms, and track window size. As a result, JSX itself (how everything looks) gets lost under tons of logic. Custom hooks are a tool for cleaning your code.
1. When to Create Your Own Hook?
Imagine you're building a house. You don't assemble a concrete mixer manually at every construction site, do you? You bring a ready one. Create a hook if:
- Duplication: You have 3 components doing the same thing (e.g., checking if user is authorized).
- Complexity: Component is hard to read due to many
useEffect. Extract them into a " black box " (hook).
2. How Does It Work?
A custom hook is a regular JavaScript function with one magical property: it can call other hooks (useState, useEffect, etc.).
Main rule: The name must start with use. This is a signal to React: " Hook logic lives inside me, watch me carefully! "
3. The " Invisibility " Magic
Many think if two components use the same useAuth(), they'll share one common password. No!
Hooks reuse only logic, not data. Every time you call a hook in a component, React creates a completely new, independent copy of that hook for that component.
4. Example: useWindowSize
Instead of writing a resize event listener in every component, we write it once:
function useWindowSize() {
const [size, setSize] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setSize(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
// Now in any component:
const width = useWindowSize();
// And your JSX is clean again!
Custom hooks turn " spaghetti code " into a set of neat professional tools.