-
Notifications
You must be signed in to change notification settings - Fork 1
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.
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
}
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
}
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.
- Use the AuthContext for global authentication state
- Keep component state local when possible
- Use the
useAuthFetchRetry
anduseFetchRetry
hooks for API calls - Consider extracting complex state logic into custom hooks
- Use the
useCallback
hook to memoize functions passed as props - Use the
useMemo
hook to memoize expensive computations
As the application grows, consider the following options for more advanced state management:
- Expand to more context types or switch to dedicated statement (e.g. React Query, Redux, ...)