React Custom Hooks
A custom hook is a JavaScript function that uses other hooks.
The only rule: name it starting with use. Like useBookFilter or useToggle. This tells React it's a hook so it can enforce the Rules of Hooks.
The Problem
Your component is doing too much:
function Bookshelf() {
const [filter, setFilter] = useState("all")
const [sort, setSort] = useState("title")
const filteredBooks = useMemo(() => {
// 30 lines of filtering logic...
}, [filter, sort])
// 50 more lines of rendering...
}Logic and UI are tangled. Hard to read, harder to test, impossible to reuse.
The Solution
Pull out the logic:
function useBookFilter() {
const [filter, setFilter] = useState("all")
const [sort, setSort] = useState("title")
const filteredBooks = useMemo(() => {
// filtering logic here
}, [filter, sort])
return { filter, setFilter, sort, setSort, filteredBooks }
}Now your component just renders:
function Bookshelf() {
const { filter, setFilter, filteredBooks } = useBookFilter()
return <BookList books={filteredBooks} />
}Clean separation. Logic in the hook, UI in the component.
A Quick Example
function useToggle(initial = false) {
const [value, setValue] = useState(initial)
const toggle = () => setValue((v) => !v)
return { value, toggle }
}Use it:
function Sidebar() {
const menu = useToggle()
return <button onClick={menu.toggle}>Menu</button>
}No more setIsOpen(!isOpen). Just menu.toggle().
What's Allowed
You can:
- Use any hooks inside
- Call other custom hooks
- Return anything (state, functions, computed values)
You can't:
- Use hooks conditionally
- Call hooks outside components/hooks
When to Make One
Consider a custom hook when:
- You're copying stateful logic between components
- A component is doing too much
- You want to test logic separately from UI
Don't refactor everything day one. Wait until you feel the pain, then extract.
Why It Matters
Custom hooks let you build abstractions that actually make sense. useAuth, useLocalStorage, useDebounce โ these aren't just patterns, they're reusable pieces that compound over time.
Your component library is your UI building blocks. Your custom hooks are your logic building blocks.
Next time you see duplicated logic, ask: could this be a hook?