Skip to main content

Other hooks inside a custom hook

Key idea

A custom hook is a regular function that uses other hooks inside itself (useState, useEffect, useMemo, useRef, useCallback, and even other custom hooks).

React does not distinguish between "built-in" hooks and your own: what matters is following the same rules of hooks.


Yes, you can - example

javascript
function useCounter(initial = 0) { const [count, setCount] = useState(initial); useEffect(() => { console.log("Counter changed:", count); }, [count]); const inc = () => setCount((c) => c + 1); const dec = () => setCount((c) => c - 1); return { count, inc, dec }; }

Here useCounter uses two built-in hooks at once:

  • useState to store the state,
  • useEffect to track changes.

And React treats this as completely normal.


You can use other custom hooks

javascript
function useUserData(userId) { const data = useFetch(`/api/users/${userId}`); const online = useOnlineStatus(); return { ...data, online }; }

useUserData uses two other custom hooks (useFetch and useOnlineStatus) - and this is fully correct.

This way, hooks can be combined, creating whole layers of reusable logic - like Lego "layers".


It is important to follow the rules of hooks

RuleWhy it matters
A hook's name must start with useReact identifies hooks by name
Call hooks only at the top levelSo the call order is not broken
Hooks cannot be called inside conditions, loops, functionsReact tracks their order by the call stack
Hooks can only be called inside function components or other hooksOutside a React context they do not work

Example of an error

javascript
function useExample(flag) { if (flag) { // Error! useState is called conditionally const [count, setCount] = useState(0); } }

React will throw an error:

javascript
Invalid hook call. Hooks can only be called inside the body of a function component.

Correct:

javascript
function useExample(flag) { const [count, setCount] = useState(0); if (flag) { // now the count value can be used } }

Summary

QuestionAnswer
Can other hooks be used inside a custom hook?Yes, you can - and that is the main purpose of custom hooks
Which hooks can be usedAny: built-in (useState, useEffect, …) and even other custom ones
What are the limitationsFollow the rules of hooks: do not call them in conditions, only at the top level
Why this is neededTo reuse logic and build hooks on top of other hooks - like a construction set

Main idea:

Custom hooks are a way to combine built-in hooks, creating reusable, clean, and predictable logic.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.