Web Unit 3 Sprint 9 - Class Components & Testing

Module 3: Custom Hooks

In this module, you'll learn about custom hooks in React, how to create them, and how to use them to share stateful logic between components. You'll understand the rules of hooks and best practices for custom hook development.

Custom hooks are a powerful feature introduced in React 16.8 that allows you to extract and reuse stateful logic between different components without changing your component hierarchy. This approach helps create cleaner, more maintainable code by separating concerns and reducing duplication.

While class components have their own lifecycle methods for handling state and effects, custom hooks provide a more flexible and composable way to share logic in functional components.

Learning Objectives

Custom hooks follow two important conventions:

  1. Their names always start with "use" (e.g., useFormInput, useLocalStorage)
  2. They can call other hooks internally (both built-in and custom hooks)

By creating custom hooks, you can:

Content

Understanding Stateful Logic

Key Concepts of Stateful Logic

  • Stateful Logic: Code that manages and responds to state changes over time
  • Separation of Concerns: Extracting logic from UI presentation
  • Mental Model: Think of hooks as functions that can "hook into" React's state and lifecycle features
  • Common Use Cases: Form handling, data fetching, authentication, animations

Composing custom hooks

Principles of Hook Composition

  • Single Responsibility: Each hook should do one thing well
  • Composition: Combine multiple hooks to create more powerful abstractions
  • Reusability: Design hooks that are generic enough to be used in different contexts
  • Implementation: Hooks can call other hooks, creating a composition pattern

Test lifecycle hooks

Testing Custom Hooks

  • React Testing Library: Use renderHook for testing hooks independent of components
  • Testing Strategy: Test the behavior and outputs, not implementation details
  • Mocking Dependencies: Use Jest mocks for external services or APIs
  • Act: Wrap state updates in act() to ensure synchronous updates during tests

Practice Activities

Additional Resources