Prepared Docs

Prepared Docs

⌘K

    Loading navigation…

User

  1. Working On Features
  2. Writing Hooks

Writing Hooks

Best practices for useEffect and custom hooks.

Quick Reference

When to use useEffect:

  • External systems only: DOM, timers, WebSocket, postMessage
  • State sync with non-React systems

When NOT to use useEffect:

  • ❌ Derived state from props (compute inline or use useMemo)
  • ❌ Data fetching (use GraphQL useQuery instead)
  • ❌ Syncing local state with props (use controlled components)

Custom hooks:

  • Extract all business logic from components
  • 🚨 ALL HOOKS MUST BE UNIT TESTED 🚨
  • Keep components display-only

When to Use useEffect

Only use useEffect for external systems outside our frontend codebase:

When NOT to Use useEffect

Derived State

Data Fetching

Syncing State with Props

Dependency Arrays

Critical rule: Only include dependencies if you want the effect to re-run when they change.

useRef for Callbacks

Use useRef for values that shouldn't trigger re-runs but need to stay current:

Cleanup Functions

Always return cleanup functions for subscriptions, timers, and event listeners:

Custom Hooks

Always extract React logic into custom hooks. Keep components display-only.

GraphQL Hooks

Testing

🚨 ALL HOOKS MUST BE UNIT TESTED 🚨

See Unit Testing for comprehensive hook testing patterns with React Testing Library.

Related Documentation

  • State Management - Zustand patterns for global state
  • Unit Testing - Testing hooks with RTL
  • GraphQL Operations - GraphQL query/mutation patterns

Reference Files

For more detailed technical guidance, see these reference files:

  • effect-when-to-use.md
  • effect-when-not-to-use.md
  • effect-dependency-arrays.md
  • effect-refs-for-callbacks.md
  • effect-cleanup.md
  • effect-syncing-state-antipattern.md
  • component-hook-extraction.md

Previous

Working on features / Forms

Next

Working on features / Styling

On this page

Quick Reference
When to Use useEffect
When NOT to Use useEffect
Derived State
Data Fetching
Syncing State with Props
Dependency Arrays
useRef for Callbacks
Cleanup Functions
Custom Hooks
GraphQL Hooks
Testing
Related Documentation
Reference Files