Custom Hooks
A custom Hook is a function that groups Hooks into one reusable piece. It starts with the word use and it can call other Hooks inside.
A Hook in a function
The function calls useState inside.
function useCounter() {
const [count, setCount] = useState(0);
return count;
}Using the custom Hook
The component calls it like any Hook.
const { count } = useCounter();
return <p>Count: {count}</p>;Sharing the logic
Each call keeps its own count.
const first = useCounter();
const second = useCounter();Example
import { useState } from 'react';
function useCounter() {
const [count, setCount] = useState(0);
function addOne() {
setCount(count + 1);
}
return { count, addOne };
}
export default function App() {
const { count, addOne } = useCounter();
return (
<div>
<p>Count: {count}</p>
<button onClick={addOne}>Count up</button>
</div>
);
}
Key points
- A custom Hook is a plain function with a name that starts with use.
- It can call useState and other Hooks inside.
- It returns the values and functions a component needs.
- Each call keeps its own state.
In this example, the useCounter function is a custom Hook. It calls useState at its top. The call makes a count that starts at zero. The function returns the count and an addOne function. The App calls useCounter and shows the count. The button runs addOne on each click.
Note
A custom Hook follows the same rules as other Hooks.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What must a custom Hook name start with?