use-cache-chat-log.ts
Overview
use-cache-chat-log.ts defines a custom React hook, useCacheChatLog, designed to manage and cache chat message events efficiently within a React application. The hook maintains an in-memory cache of event lists grouped by unique message IDs, enabling selective retrieval, filtering, and updating of chat event data.
This hook is particularly useful in chat or messaging applications where events related to messages (such as typing indicators, message content, message status, etc.) arrive asynchronously and need to be cached and filtered for display or processing without redundant network requests.
Exports
ExcludeTypes (constant)
Type:
MessageEventType[]Description: An array of MessageEventType enum values that are excluded when filtering event lists in certain hook functions. Currently includes:
MessageEventType.MessageMessageEventType.MessageEnd
These typically represent raw or terminal message events that are often filtered out when focusing on intermediary or non-message-specific events.
useCacheChatLog() (custom React hook)
Purpose
Manages stateful caching of chat event logs keyed by message IDs, providing utility functions to add, clear, and filter event data.
Returns
An object exposing the following properties and functions:
Name | Type | Description |
|---|---|---|
|
| The current list of events associated with the current message ID. |
| Filtered events of the current message ID excluding events of types in | |
| Function that returns filtered events for a given message ID excluding | |
| Setter function to directly update the entire event list state. | |
| Clears all cached events and resets the state. | |
| Adds new events to the existing list and updates the cache for a specific message ID. | |
| Retrieves events of a specific event type for the current message ID. | |
| Retrieves all events for a specific message ID. | |
|
| Setter to update the currently active message ID. |
|
| The currently active or selected message ID. |
Types & Interfaces (Imported)
IEventList: An array type representing a list of event objects (INodeEvent[]).INodeEvent: Interface representing an individual event object, which contains at least properties likemessage_idandevent.MessageEventType: Enum or type defining various possible event types related to messages.
These are imported from '@/hooks/use-send-message' and are critical for typing and filtering events.
Detailed Explanation of Hook Functions and State
State Variables
eventList(IEventList): Stores the currently active list of events related to the selected message.messageIdPool(Record<string, IEventList>): A dictionary mapping message IDs to their corresponding event lists. Acts as a cache.currentMessageId(string): Holds the message ID currently in focus or being viewed.
useEffect
Synchronizes the
messageIdPoolcache with the currenteventListwhenevercurrentMessageIdoreventListchanges. It updates or inserts the currenteventListunder thecurrentMessageIdkey.
filterEventListByMessageId(messageId: string): INodeEvent[] | undefined
Filters and returns events from the cache for a specific
messageId.Only returns events where
event.message_id === messageId.Returns undefined if no events exist for that ID.
filterEventListByEventType(eventType: string): INodeEvent[] | undefined
Filters and returns events of a specific
eventTypefor thecurrentMessageId.Useful for extracting events of a particular type (e.g., typing indicators) for the current message.
clearEventList()
Resets both the current event list and the entire message ID cache.
Useful when resetting the chat session or clearing state on logout.
addEventList(events: IEventList, message_id: string)
Adds new events to the existing
eventListand updates the cache for the givenmessage_id.This method ensures that new events are appended and the cache remains consistent.
The
eventListstate updates trigger theuseEffectto sync the cache.
currentEventListWithoutMessage (Memoized)
Returns the filtered list of events for the
currentMessageId, excluding events whoseeventtype is in theExcludeTypesarray.This helps to get intermediary events without the "message" or "message end" types.
currentEventListWithoutMessageById(messageId: string): INodeEvent[]
Similar to the above but for an arbitrary
messageId.Returns filtered events excluding
ExcludeTypesfor any message ID.
Usage Example
import { useCacheChatLog } from './use-cache-chat-log';
function ChatComponent() {
const {
eventList,
addEventList,
filterEventListByEventType,
setCurrentMessageId,
currentMessageId,
} = useCacheChatLog();
useEffect(() => {
setCurrentMessageId('message-123');
}, []);
useEffect(() => {
// Simulate receiving new events
const newEvents = [
{ message_id: 'message-123', event: 'typing', data: {...} },
{ message_id: 'message-123', event: 'message', data: {...} },
];
addEventList(newEvents, 'message-123');
}, [addEventList]);
const typingEvents = filterEventListByEventType('typing');
return (
<div>
<h3>Current Message ID: {currentMessageId}</h3>
<div>Typing events count: {typingEvents?.length ?? 0}</div>
{/* Render chat UI */}
</div>
);
}
Implementation Details and Algorithms
State Synchronization: The hook uses a combination of React state (
useState) anduseEffectto keep the cache (messageIdPool) synchronized with the actively manipulatedeventList.Filtering Logic: Filtering is implemented via standard JavaScript
Array.prototype.filtermethods combined with predicate checks against message IDs and event types.Exclusion Logic: The
ExcludeTypesarray defines event types to exclude in certain filtered views, ensuring flexibility in rendering or processing only relevant events.Memoization:
useMemooptimizes filtering computations for the current message ID, preventing unnecessary recalculations on unrelated state updates.Callback Memoization:
useCallbackmemoizes filter and mutator functions to maintain stable references and improve performance when used as dependencies or props.
Interaction with Other Parts of the System
Depends on types and event definitions from
'@/hooks/use-send-message', indicating it integrates tightly with the message sending and event system of the application.Likely used in components or hooks responsible for rendering chat messages, handling incoming message events, or managing message state lifecycle.
Provides a caching layer that helps avoid redundant fetches or computations by storing event lists keyed by message IDs, which enhances performance and responsiveness.
Can be integrated with UI components to display filtered event streams per message, such as typing indicators, message edits, or delivery status updates.
Mermaid Diagram
flowchart TD
A[useCacheChatLog Hook] --> B[eventList (IEventList)]
A --> C[messageIdPool (Record<string, IEventList>)]
A --> D[currentMessageId (string)]
A --> E[useEffect: Sync messageIdPool with eventList and currentMessageId]
A --> F[filterEventListByMessageId(messageId)]
A --> G[filterEventListByEventType(eventType)]
A --> H[clearEventList()]
A --> I[addEventList(events, messageId)]
A --> J[currentEventListWithoutMessage (memoized)]
A --> K[currentEventListWithoutMessageById(messageId)]
A --> L[setEventList(state setter)]
A --> M[setCurrentMessageId(state setter)]
Summary
use-cache-chat-log.ts provides a robust, performant caching mechanism for chat message events with filtering and update utilities. Its design leverages React hooks to maintain synchronization between a cache and the current event list, enabling flexible event retrieval by message ID and event type. This hook is essential for chat applications needing efficient event management and selective rendering based on message contexts.