Custom hook
- React Native course
- Intermediate
- Lesson 7/116
- 5 min
Learn to write custom hooks.
What is a custom hook?
A custom hook extracts shared state logic that you can use in many components. Its name starts with use; for example useToggle, useCounter. This naming is required; React's lint tools rely on it.
A custom hook is just a function; it can call other hooks inside. You combine hooks like useState and useEffect to write a reusable piece of logic. Custom hooks reduce component clutter and make code easier to test.
Hook principles
When you write a custom hook you follow two principles. First: hooks are called only at the top level of a component or another hook; not inside loops, conditions or nested functions. Second: call multiple hooks in the same order every time.
These principles let React track hooks correctly. Otherwise state gets mixed up. A custom hook can return a single value, an array or an object. The return [value, setValue] pattern is common; the calling component does const [v, setV] = useMyHook() destructuring.
Practice Your first custom hook
Write a custom hook named useGreeting. Inside, hold a name state with useState (initial value "guest"). The hook returns the array [name, setName].
Starter code
// Import useState
// Write the useGreeting custom hook
// Hold name state with useState
// Return [name, setName]Sample solution
import { useState } from "react";
function useGreeting() {
const [name, setName] = useState("guest");
return [name, setName];
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should a custom hook name start with?
function useToggle(initial) { /* ... */ }- handle
- with
- use Correct answer
- on
Explanation: A custom hook name starts with use.
2 Complete the hook name
function ____(initial) {
const [value, setValue] = useState(initial);
return [value, setValue];
}
function useToggle(initial) {
const [value, setValue] = useState(initial);
return [value, setValue];
}
Explanation: The hook name is useToggle.
3 Match each piece to its role
| Term | Meaning |
|---|---|
useToggle |
Custom hook name |
useState |
Holds state |
return [v, setV] |
Returns the value |
use prefix |
Hook marker |