Today I Truly Understood Custom Hooks (And Built My Own)
Source: Dev.to
Overview
Today felt different. Not because I learned a new React feature, but because I leveled up how I think about code structure. I didn’t just write components—I started building my own hooks, and that changed everything.
While working on my project I noticed a pattern:
- Keyboard logic in one component
- LocalStorage logic in another
- Movie‑fetching logic somewhere else
Lots of useEffect, lots of repeated patterns, everything tightly coupled to the UI. That’s when I realized this logic doesn’t belong to the UI—it belongs in its own abstraction. That’s when I truly understood custom hooks.
Custom hooks are how you separate behavior from UI. They let you:
- Reuse logic
- Isolate side effects
- Simplify components
- Think in features instead of files
useKey — Encapsulating Keyboard Behavior
I built a hook that:
- Listens for a specific key
- Runs an action when that key is pressed
- Automatically cleans up after itself
The important idea is that the component should not care how the event listener works. Now my component reads like business logic, not plumbing.
useLocalStorage — State That Persists Automatically
This hook taught me something powerful: a hook can feel like state, but be smarter than state.
The hook:
- Reads the initial value from
localStorage - Keeps React state in sync
- Automatically saves on every change
So instead of writing storage logic everywhere, I just say: “Give me persistent state.” That’s a huge architectural upgrade.
useMovies — The Moment It All Clicked
This was the real turning point. I moved the following responsibilities into a single hook:
- Fetching data
- Loading state
- Error handling
AbortControllerusage- Data cleanup
- Business rules
Now the component doesn’t know how fetching works, how errors are handled, or how race conditions are prevented. It only knows: “Give me movies, loading, and error.” This clean separation of concerns makes the component much simpler.
Takeaways
- Custom hooks are your own React API for the app.
Instead of repeatedly writinguseEffect,useState,fetch,addEventListener,localStorage, you writeuseMovies,useKey,useLocalStorage. - The mindset shifts from “How do I implement this?” to “What hook should exist for this behavior?”
- Components = UI only
- Hooks = behavior, side effects, logic
- If logic feels reusable → it deserves a hook.
- If a component feels heavy → extract a hook.
Today wasn’t just about understanding custom hooks; it was about starting to build with this new mindset. My components are smaller, and most importantly, I’m no longer just using React—I’m building on top of it.