State Management
Relevant source files
The following files were used as context for generating this wiki page:The application employs a multi-layered state management strategy, combining React's built-in features with specialized libraries to handle different types of state. Global UI state, such as theme and language, is managed via React Context. Authentication state is handled by a custom hook that abstracts platform-specific logic. Server state and data caching are managed by TanStack Query (React Query) and tRPC. Finally, transient, component-level state is handled using the useState hook.
This tiered approach separates concerns, ensuring that global concerns are handled at the application root, server data has its own caching and lifecycle management, and local UI state remains encapsulated within the components that need it.
State Management Strategies
| Strategy | Tools Used | Purpose | Examples |
|---|---|---|---|
| Global UI State | React Context, useState, useEffect | Manages application-wide state that affects the entire UI and needs to be persisted. | Theme (light/dark), selected language. |
| Authentication State | Custom Hook (useAuth), React Context | Manages user session, authentication status, and user information across platforms. | user, isAuthenticated, loading. |
| Server State | TanStack Query, tRPC | Fetches, caches, and synchronizes data from the server. | User data, API responses. |
| Local Component State | useState | Manages state that is local to a single component, such as form inputs or UI toggles. | isAnalyzing, selectedFile, analysisResults. |
Sources: [`app/_layout.tsx`](https://github.com/Pirzl/aidoit4u-mobile-app/blob/HEAD/%60app/_layout.tsx%60), [`hooks/use-auth.ts`](https://github.com/Pirzl/aidoit4u-mobile-app/blob/HEAD/%60hooks/use-auth.ts%60), [`lib/theme-provider.tsx`](https://github.com/Pirzl/aidoit4u-mobile-app/blob/HEAD/%60lib/theme-provider.tsx%60), [`lib/language-context.tsx`](https://github.com/Pirzl/aidoit4u-mobile-app/blob/HEAD/%60lib/language-context.tsx%60), [`app/(tabs)/analyze.tsx`](https://github.com/Pirzl/aidoit4u-mobile-app/blob/HEAD/%60app/(tabs)/analyze.tsx%60)
Global State Management (React Context)
Global state that affects the entire application's UI is managed through a set of React Context providers. These providers are instantiated at the top level of the application in app/_layout.tsx to ensure the state is available to all components.
This diagram illustrates the provider hierarchy in the root layout.
Sources: app/_layout.tsx:16-49
Authentication State (useAuth)
Authentication is managed by the useAuth custom hook, which provides user data, loading status, and authentication functions. It abstracts the platform-specific logic for handling sessions.
- Web Platform: Relies on cookie-based authentication. It calls the
/api/auth/meendpoint to fetch user data. - Native Platforms (iOS/Android): Relies on a session token stored securely. It first checks for a cached user, then validates the session with the stored token.
The hook returns an object with the current authentication state and methods to interact with it.
| Property | Type | Description |
|---|---|---|
user | Auth.User | null | The authenticated user object, or null if not logged in. |
loading | boolean | true while the initial user fetch is in progress. |
error | Error | null | An error object if fetching the user fails. |
isAuthenticated | boolean | A derived boolean indicating if a user is currently logged in. |
refresh | () => Promise<void> | A function to manually re-fetch the user data. |
logout | () => Promise<void> | A function to log the user out, clearing session tokens and user data. |
Sources: hooks/use-auth.ts:10-18
The following sequence diagram shows the data flow when fetchUser is called within the useAuth hook.
Sources: hooks/use-auth.ts:14-63
Theme State (ThemeProvider)
The ThemeProvider manages the application's color scheme (light or dark mode). It uses AsyncStorage to persist the user's preference across app sessions under the key theme-preference.
- Context:
ThemeContext - Provider:
ThemeProvider - Hook:
useTheme() - Provided State:
theme('light' or 'dark'),isDark(boolean),setTheme((prev) => ...) - Persistence Key:
theme-preference
The useColors hook is a consumer of this context, providing direct access to the theme-specific color palette.
Sources: lib/theme-provider.tsx, hooks/use-colors.ts
Language State (LanguageProvider)
The LanguageProvider manages the application's display language. It supports 'ES', 'EN', and 'DE'. Similar to the theme, it uses AsyncStorage to persist the selected language under the key language-preference.
- Context:
LanguageContext - Provider:
LanguageProvider - Hook:
useLanguage() - Provided State:
language('ES', 'EN', or 'DE'),setLanguage((prev) => ...) - Persistence Key:
language-preference
Components use the useLanguage hook and the getTranslation utility to display text in the currently selected language.
Sources: lib/language-context.tsx, lib/translations.ts:1-2
Server State Management (React Query & tRPC)
The application uses TanStack Query (via @tanstack/react-query) and tRPC to manage server state. This is configured in app/_layout.tsx, where the QueryClientProvider and trpc.Provider wrap the main application content.
The QueryClient is configured with the following default options:
refetchOnWindowFocus: false: Prevents automatic data re-fetching when the app window regains focus, which is a common optimization for mobile apps.retry: 1: Automatically retries failed queries once.
This setup handles the complexities of remote data, including caching, background updates, and request deduplication.
Sources: app/_layout.tsx:53-65
Local Component State (useState)
For state that is confined to a single component, the application uses the standard React useState hook. This is ideal for managing UI state, form inputs, and other transient data that doesn't need to be shared globally.
The AnalyzeScreen is a clear example of this pattern. It uses useState to manage several pieces of local state:
selectedFile: Stores the file selected by the user for analysis.documentName: Holds the text pasted by the user.isAnalyzing: A boolean flag to track the analysis process and disable the UI.analysisResults: Stores the results from the analysis API to be displayed to the user.
The following flowchart illustrates the state transitions within the AnalyzeScreen component.