Skip to main content

State Management

Server State (TanStack Query)

We refer to "Server State" as any data that comes from the API (User profile, List of cameras, Alerts). We use TanStack Query (React Query) to manage this because:

  1. Deduplication: Multiple components can request useUser() without spamming the API.
  2. Caching: Instant navigation between pages.
  3. Invalidation: When we mutate data (e.g., updateCameraName), we simply call queryClient.invalidateQueries(['cameras']) to refresh the UI automatically.

Global Client State (Context)

AuthProvider

Wraps the entire application.

  • Responsibility: Checks for a valid JWT in storage on mount.
  • Handling 401s: If the API returns 401, it automatically redirects to /login and wipes the session.

ThemeProvider

Manages Light/Dark mode preference (persisted in LocalStorage).

Authentication Flow

  1. Login: api.post('/login') returns { token, refreshToken }.
  2. Storage: We use TokenManager (singleton) to store the token in HTTP-only cookies (for security) or LocalStorage (for ease of access).
  3. Requests: The custom fetch wrapper (or Axios interceptor) injects Authorization: Bearer <token> into every request.
  4. Sockets: useSocketManager also independently reads the token to authenticate websockets.