Summary - Custom hooks
- React Native course
- Intermediate
- Lesson 12/116
- 5 min
Combine useToggle, useCounter and usePrevious to write a hook library.
Summary - Custom hooks
In this group you learned to write custom hooks. useToggle flips a boolean, useCounter raises and lowers a number, usePrevious gives the previous value. With hook composition you combine them in one hook.
Now you will write these three hooks side by side like a library. Each lives in one file and you can import it into any component. This balance keeps the codebase simple and scalable; it is a pattern you will meet in real apps.
Practice Write useToggle
Write the useToggle custom hook. Hold a value with useState (initial value initial). The toggle function sets !value. The hook returns [value, toggle].
Starter code
// Import useState
// Write the useToggle custom hook
// Start value state with initial
// toggle sets !value
// Return [value, toggle]Sample solution
import { useState } from "react";
function useToggle(initial) {
const [value, setValue] = useState(initial);
const toggle = () => setValue(!value);
return [value, toggle];
}Practice Write useCounter
Write the useCounter custom hook. Hold a count with useState (initial value initial). The increment function adds n (defaults to 1). The hook returns [count, increment].
Starter code
// Import useState
// Write the useCounter custom hook
// Start count state with initial
// increment adds n
// Return [count, increment]Sample solution
import { useState } from "react";
function useCounter(initial) {
const [count, setCount] = useState(initial);
const increment = (n = 1) => setCount(count + n);
return [count, increment];
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does usePrevious keep?
const prev = usePrevious(count);- The next render's value
- The initial value forever
- The current render's value
- The previous render's value Correct answer
Explanation: usePrevious keeps the value from the previous render.
2 Match the hook to its role
| Term | Meaning |
|---|---|
useToggle |
On/off |
useCounter |
Raise/lower |
usePrevious |
Old value |
useRef |
Mutable reference |
3 Complete the hook name
function ____(initial) {
const [count, setCount] = useState(initial);
return [count, setCount];
}
function useCounter(initial) {
const [count, setCount] = useState(initial);
return [count, setCount];
}
Explanation: The hook name is useCounter.