Skip to content

State Management

Simon Gibson edited this page Sep 9, 2024 · 1 revision

State Management

NeRF-or-Nothing uses React's Context API for global state management, primarily for handling user authentication. This approach provides a balance between simplicity and scalability for the current needs of the application.

AuthContext

The main state management solution is implemented in AuthContext.tsx. Try to avoid integrating global state into components unless absolutely necessary.

Key features:

  • Manages user authentication state
  • Provides login and logout functions
  • Stores JWT token and username in localStorage
  • Handles initial auth state loading

Usage:

import { useContext } from 'react';
import { AuthContext } from '../../Context/AuthContext';

function MyComponent() {
  const { isAuthenticated, token, username, login, logout } = useContext(AuthContext);
  
  // Use these values and functions as needed
}

Local Component State

For component-specific state, we use the useState hook. This is suitable for managing local UI state that doesn't need to be shared across multiple components.

Example:

import { useState } from 'react';

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);
  
  // Use isLoading and setIsLoading as needed
}

Data Fetching and Caching

For data fetching and caching, we currently use a custom approach with the useAuthFetchRetry hook. This hook handles authentication, retries, and basic error handling for API calls.

Consider implementing a more robust data fetching and caching solution (e.g., React Query, SWR) if the application's data management needs grow more complex.

Best Practices

  1. Use the AuthContext for global authentication state
  2. Keep component state local when possible
  3. Use the useAuthFetchRetry and useFetchRetry hooks for API calls
  4. Consider extracting complex state logic into custom hooks
  5. Use the useCallback hook to memoize functions passed as props
  6. Use the useMemo hook to memoize expensive computations

Future Considerations

As the application grows, consider the following options for more advanced state management:

  1. Expand to more context types or switch to dedicated statement (e.g. React Query, Redux, ...)