Skip to main content

Best Practices

1. Choose the Right State Management

State TypeUseExample
Global sharedReact ContextTeams, permissions
Form dataReact Hook FormAll forms
Table stateTanStack Table + ContextData tables
Local UIuseStateModals, toggles
ShareableURL paramsFilters, pagination

2. Context Best Practices

Do:

  • Use Context for truly global state
  • Provide initial values from Server Components
  • Use TypeScript for type safety
  • Throw errors if used outside provider

Don't:

  • Overuse Context (causes unnecessary re-renders)
  • Store frequently changing state in Context
  • Use Context for server-only data

3. Form State Best Practices

Do:

  • Use React Hook Form for all forms
  • Validate with Zod schemas
  • Use form context for nested components
  • Handle loading and error states

Don't:

  • Use controlled inputs without React Hook Form
  • Validate in component (use Zod)
  • Store form state in Context

4. Table State Best Practices

Do:

  • Cache query results
  • Sync state with URL
  • Use server-side filtering/sorting
  • Debounce rapid filter changes

Don't:

  • Fetch data on every render
  • Store table data in Context
  • Use client-side filtering for large datasets

5. Performance Optimization

  • Memoization: Use useMemo and useCallback for expensive computations
  • Debouncing: Debounce search inputs and filters
  • Caching: Cache table query results
  • Lazy loading: Load data only when needed
  • Code splitting: Split large contexts into smaller ones

6. State Updates

  • Immutable updates: Always create new objects/arrays
  • Functional updates: Use functional setState when depending on previous state
  • Batch updates: React batches state updates automatically
  • Error handling: Always handle errors in state updates

Summary

State Management SolutionUse CaseLocation
React ContextGlobal/shared statesrc/context/
React Hook FormForm statesrc/components/forms/
TanStack TableTable statesrc/components/tables/
useStateLocal component stateThroughout components
URL ParamsShareable stateNext.js navigation

Key Takeaways:

  • Context for global state - Teams, permissions, petition data
  • React Hook Form for forms - All form state management
  • TanStack Table for tables - Filtering, sorting, pagination
  • URL params for shareability - Filters, pagination, steps
  • Local state for UI - Modals, toggles, temporary state

The application uses a hybrid approach combining multiple state management strategies, each optimized for its specific use case.