What is a custom hook?
- React course
- Intermediate
- Lesson 1/80
- 4 min
Learn that functions starting with use are reusable logic pieces.
What is a custom hook?
A custom hook is a JavaScript function you write whose name starts with use. It can call other hooks (useState, useEffect, etc.) inside and lets you share logic between components.
For example, if several components use the same counter logic, you can move it into a hook called useCounter and call it in each component. This prevents code duplication and eases maintenance.
Two rules: its name must start with use, and it must be called only at the top level (not inside loops, conditions, or nested functions). These rules let React track hook order.
Two rules
Custom hooks follow two rules. First, naming: the use prefix is required; this lets React know it's a hook and linters recognize it.
Second, call site: hooks are only called at the top level of a component. Not in loops, if blocks, or nested functions. This lets React call hooks in the same order on every render.
Follow these two rules and you can safely share hooks between components. Otherwise React loses hook order and throws.
Practice useCounter skeleton
Complete the skeleton. Write a custom hook called useCounter. Define count and setCount with useState(0). Return an increment function: () => setCount(c => c + 1). Export the hook.
Starter code
import { useState } from "react";
// Write the useCounter hook hereSample solution
import { useState } from "react";
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount((c) => c + 1);
return increment;
}
export default useCounter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a custom hook name start with?
- hook
- use Correct answer
- custom
- get
Explanation: Custom hook names start with use.
2 Logic sharing
To use the same logic in multiple components, write a ____.
To use the same logic in multiple components, write a custom hook.
Explanation: Logic is shared via a custom hook.
3 Match the custom hook concepts
| Term | Meaning |
|---|---|
use prefix |
Naming |
top level |
Call site |
useState |
Called inside |
sharing |
Purpose |