Implementation:Langgenius Dify UseMitt
| Knowledge Sources | |
|---|---|
| Domains | Frontend, React_Hooks |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
A React hook that wraps the mitt event emitter library, providing a declarative subscription mechanism with automatic cleanup tied to the React component lifecycle.
Description
useMitt is a generic React hook that creates or wraps a mitt event emitter and returns a useSubscribe function and an emit function. The emitter instance is stored in a useRef to persist across renders. If an external emitter is passed and differs from the current one, the hook clears all wildcard listeners and swaps to the new emitter. The useSubscribe function is itself a hook (intended to be called inside a component body) that registers an event handler via useEffect, automatically unsubscribing on cleanup. It supports an enabled option (defaulting to true) that allows conditional subscription. The hook uses a merge utility to combine default options with user-provided options. The generic Events type parameter allows full type safety for event names and payloads.
Usage
Use this hook to create lightweight, type-safe pub/sub communication channels between React components. It is suitable for sibling component communication, custom event buses within a feature module, or any scenario where React context or prop drilling is too heavy for simple event notifications.
Code Reference
Source Location
- Repository: Langgenius_Dify
- File: web/hooks/use-mitt.ts
- Lines: 1-74
Signature
type _Events = Record<EventType, unknown>
type UseSubscribeOption = {
enabled: boolean // default: true
}
type UseMittReturn<Events extends _Events> = {
useSubscribe: ExtendedOn<Events>
emit: Emitter<Events>['emit']
}
function useMitt<Events extends _Events>(
mitt?: Emitter<Events>,
): UseMittReturn<Events>
Import
import { useMitt } from '@/hooks/use-mitt'
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| mitt | Emitter<Events> | No | An optional external mitt emitter instance; if omitted, a new emitter is created internally |
Outputs
| Name | Type | Description |
|---|---|---|
| useSubscribe | ExtendedOn<Events> | A hook function to subscribe to events with automatic cleanup; accepts an event type, handler, and optional enabled flag |
| emit | Emitter<Events>['emit'] | The emit function from the underlying mitt emitter to dispatch events |
Usage Examples
Basic Event Bus Between Components
import { useMitt } from '@/hooks/use-mitt'
type MyEvents = {
'item-selected': { id: string }
'search-cleared': undefined
}
function ParentComponent() {
const { useSubscribe, emit } = useMitt<MyEvents>()
return (
<>
<ListComponent useSubscribe={useSubscribe} />
<ToolbarComponent emit={emit} />
</>
)
}
function ListComponent({ useSubscribe }: { useSubscribe: any }) {
useSubscribe('item-selected', (payload) => {
console.log('Selected item:', payload.id)
})
return <div>List</div>
}
function ToolbarComponent({ emit }: { emit: any }) {
return (
<button onClick={() => emit('item-selected', { id: '123' })}>
Select Item
</button>
)
}
Conditional Subscription
import { useMitt } from '@/hooks/use-mitt'
type Events = { 'data-update': { value: number } }
function ConditionalListener({ isActive }: { isActive: boolean }) {
const { useSubscribe } = useMitt<Events>()
useSubscribe(
'data-update',
(payload) => console.log('Updated:', payload.value),
{ enabled: isActive },
)
return <div>Listener is {isActive ? 'active' : 'inactive'}</div>
}