Caching Feature - abhiram-shaji/Langroove GitHub Wiki
useChat.ts
Caching Feature in This document provides an overview of the caching mechanisms implemented in the useChat
hook, focusing exclusively on the caching functionality.
Overview
The useChat
hook facilitates real-time chat functionality by managing messages, user input, and chat-specific settings such as languages. Caching is implemented in two primary areas to optimize resource usage and improve performance:
- Language Settings Caching: Reduces redundant database calls for user and recipient language preferences.
- Messages Caching: Leverages Firestore's local cache for efficient real-time message fetching.
Language Settings Caching
Purpose
The chat application retrieves and caches the user's and recipient's language preferences to:
- Minimize repeated database requests.
- Provide faster initialization of language settings during chat sessions.
Implementation
-
Functionality:
- The
ensureChatLanguage
function is called to fetch or derive theuserLanguage
andrecipientLanguage
for the chat session. - If the language settings are cached (locally or in the database), they are retrieved directly without re-fetching.
- The
-
Code Snippet:
useEffect(() => { const initializeChatLanguages = async () => { const { userLanguage, recipientLanguage } = await ensureChatLanguage(chatId, currentUser.uid, recipientId); setUserLanguage(userLanguage); setRecipientLanguage(recipientLanguage); }; initializeChatLanguages(); }, [chatId, currentUser, recipientId]);
-
Process:
- The
initializeChatLanguages
function runs when the component mounts or when thechatId
,currentUser
, orrecipientId
changes. - The languages are stored in the component's state variables (
userLanguage
,recipientLanguage
) for reuse during the session.
- The
Messages Caching
Purpose
Firestore's real-time listener includes a local caching mechanism that:
- Fetches messages from the cache for immediate use.
- Updates the messages with server changes when online.
Implementation
-
Functionality:
- The Firestore
onSnapshot
listener automatically integrates local caching. - Cached messages are loaded initially, reducing latency.
- Any updates from the server are merged seamlessly.
- The Firestore
-
Code Snippet:
useEffect(() => { const chatDocRef = firestoreDoc(db, "chats", chatId); const messagesRef = collection(chatDocRef, "messages"); const messagesQuery = query(messagesRef, orderBy("createdAt", "asc")); const unsubscribe = onSnapshot(messagesQuery, (snapshot) => { const loadedMessages: Message[] = snapshot.docs.map(doc => ({ id: doc.id, text: doc.data().text, senderId: doc.data().sender, senderType: doc.data().sender === currentUser?.uid ? "me" : "other", })); setMessages(loadedMessages); }); return () => unsubscribe(); // Clean up listener on unmount }, [chatId, currentUser]);
-
Process:
- Firestore's caching reduces unnecessary server requests, especially in offline or low-connectivity scenarios.
- The
onSnapshot
listener keeps the messages list (messages
) up-to-date by reflecting both cached and live data.
Benefits of Caching
- Performance: Faster initial load times due to cached data.
- Reduced Server Load: Fewer database reads, especially for frequently accessed chats.
- Offline Support: Cached data ensures continuity when the user is offline.
Notes
- Ensure
ensureChatLanguage
efficiently handles cache invalidation to reflect any updates in user or recipient language settings. - The Firestore caching behavior is automatic but can be fine-tuned if specific requirements arise (e.g., manual cache clear, advanced query configurations).