Custom Hooks vs Utility Functions
What you'll learn: When to extract logic into a custom Hook versus a plain utility function.
The Core Difference
Custom Hooks and utility functions both help you reuse code, but they serve fundamentally different purposes:
Custom Hooks can use React's built-in hooks (like useState, useEffect, useRef) and tap into React's component lifecycle. They follow Hook rules and must start with "use".
Utility functions are plain JavaScript functions that perform calculations or transformations without any React features. They don't need state, effects, or lifecycle—just input in, output out.
When to Use Each
Choose a Custom Hook when:
- You need component state (
useState) - You need side effects (
useEffect) - You need refs, context, or other React features
- The logic depends on the component lifecycle (mount, unmount, updates)
Example: useLocalStorage needs useState to store the value and useEffect to sync with localStorage on changes.
Choose a Utility Function when:
- You're transforming data (format dates, filter arrays, calculate totals)
- Pure computation with no side effects
- No state or lifecycle needed
- Can be used anywhere, even outside React
Example: A formatCurrency function that takes a number and returns a formatted string—pure transformation, no React needed.
The Mental Model
Think of custom Hooks as "React-aware helpers" that plug into your component's lifecycle. Utility functions are "dumb calculators" that just process inputs and return outputs, completely unaware React even exists.
Key Takeaway: Use custom Hooks when you need React features (state, effects, lifecycle); use utility functions for pure data transformations. Don't force Hook syntax on simple calculations, and don't write plain functions when you need React's component features.