Hook composition
- React Native course
- Intermediate
- Lesson 11/116
- 5 min
Learn to compose hooks.
What is hook composition?
Hook composition is combining multiple hooks inside a single custom hook. This way complex logic hides behind one call; components stay simple. Custom hooks can call other hooks, so this is a natural approach.
Example: a hook named useUserStatus can combine useToggle and useCounter to manage online user count and menu state at once. The component just writes const [count, toggle] = useUserStatus(); the details stay hidden. This improves reusability in large apps.
A composition example
A useGameScore hook can combine useCounter and usePrevious. While the score grows the old score is shown too; the player sees the gain from the last move. The component just writes const [score, increment, prev] = useGameScore().
When you compose, make sure each sub-hook can run on its own. If hooks share state, do it through parameters and return values; avoid assigning from outside. This approach helps both testing and reusability.
Practice Combine two hooks
Write the useScoreWithPrev custom hook. Inside call useCounter(0) and usePrevious(count). The hook returns [count, increment, prev].
Starter code
// Import useCounter and usePrevious
// Write the useScoreWithPrev custom hook
// Get count and increment with useCounter
// Get prev with usePrevious
// Return [count, increment, prev]Sample solution
import { useCounter, usePrevious } from "./hooks";
function useScoreWithPrev() {
const [count, increment] = useCounter(0);
const prev = usePrevious(count);
return [count, increment, prev];
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Call the hook
function useFeature() {
const [count, increment] = ____(0);
return [count, increment];
}
function useFeature() {
const [count, increment] = useCounter(0);
return [count, increment];
}
Explanation: The useCounter call returns the values.
2 Match the composition scenario
| Term | Meaning |
|---|---|
useCounter |
Raises the score |
usePrevious |
Gives old score |
useToggle |
Opens the menu |
useGameScore |
Combines all three |
3 What does composition give you?
function useGameScore() {
const [score] = useCounter(0);
const prev = usePrevious(score);
return [score, prev];
}- Slower execution
- Less reusability
- A lot of logic in one call Correct answer
- Longer components
Explanation: Composition gives a lot of logic in one call.