0Pricing
React Native Academy · Lesson

Writing Custom Hooks

Extract stateful logic into a reusable custom hook, share it between two components, and follow the naming convention and rules of hooks.

What Are Custom Hooks?

Custom hooks are JavaScript functions whose names start with use and that may call other React hooks inside them. They let you extract stateful logic from a component into a reusable function. The logic is shared, but each component that calls the custom hook gets its own isolated state — custom hooks are not singletons.

The Rules of Hooks Apply to Custom Hooks

Custom hooks follow the same rules as built-in hooks: only call hooks at the top level (not inside loops or conditions), and only call hooks from React function components or other custom hooks. The use naming prefix is required — it signals to React and linters that the function follows these rules.

// Valid custom hook — starts with 'use'
function useCounter(initialValue) {
  const [count, setCount] = useState(initialValue);
  const increment = () => setCount(c => c + 1);
  const decrement = () => setCount(c => c - 1);
  const reset = () => setCount(initialValue);
  return { count, increment, decrement, reset };
}

All lessons in this course

  1. useRef for DOM Nodes and Mutable Values
  2. useReducer for Complex State Logic
  3. useCallback and useMemo for Performance
  4. Writing Custom Hooks
← Back to React Native Academy