Course contentsShow
← React
Lesson 1001 of 2,39625. Custom HooksFree lesson

Extracting for Testability vs Reusability

Distinguish between extracting hooks to test complex logic in isolation versus extracting for cross-component reuse.

Extracting for Testability vs Reusability

You'll learn the two distinct reasons for extracting custom hooks—and why they're not always the same thing.

The Two Different "Why"s

When you pull logic into a custom hook, you're usually motivated by one of two goals:

For reusability: You have the same logic in multiple components (the three-strike rule). You want to write it once and share it everywhere.

For testability: You have complex logic in a single component that's hard to test. By extracting it into a hook, you can test that logic in isolation—without mounting the entire component, mocking APIs, or dealing with UI concerns.

Same Technique, Different Purpose

Both scenarios use the same mechanism (a custom hook), but the intent differs:

  • Reuse-driven extraction asks: "Where else will I use this?"
  • Test-driven extraction asks: "Can I verify this logic without the component?"

A custom hook for complex date calculations might only live in one component, but extracting it means you can write unit tests that cover edge cases without rendering anything. That's valuable even if you never reuse it.

Conversely, a useToggle hook might be trivially simple but get reused everywhere. You extract it for DRY principles, not because it's hard to test inline.

The Overlap

Sometimes you get both: complex logic that's also shared. That's the sweet spot. But don't feel you must reuse something just because you extracted it for testing—and don't avoid extraction just because "it's only used once."

Key Takeaway: Extract custom hooks for reusability when logic repeats across components, or for testability when complexity makes isolated testing worthwhile—these are independent, valid reasons.