react-eventizer v0.1.9
react-eventizer
A lightweight, zero-dependency React event bus with full TypeScript support. Enables decoupled component communication using a pub/sub model.
Features
- ð Simple Pub/Sub API: Easy-to-use methods for subscribing to and emitting events
- ð Type-Safe: Full TypeScript support with generics to enforce event types and payloads
- âïļ React Integration: Seamless integration with React via Context and custom hooks
- ðŠķ Lightweight: Zero external dependencies, minimal footprint
- ð§Đ Decoupled Communication: Communicate between components without prop drilling or complex state management
Installation
npm install react-eventizer
# or
yarn add react-eventizer
Quick Start
1. Define your event map
// events.ts
import { EventMap as BaseEventMap } from 'react-eventizer';
export interface EventMap extends BaseEventMap {
'user:login': { username: string; id: number };
'notification:new': { message: string; type: 'info' | 'warning' | 'error' };
'theme:change': 'light' | 'dark';
'modal:close': void;
}
2. Set up the provider
// App.tsx
import React from 'react';
import { Eventizer, EventizerProvider } from 'react-eventizer';
import { EventMap } from './events';
const App: React.FC = () => {
// Create an event bus instance
const eventBus = React.useMemo(() => new Eventizer<EventMap>(), []);
return (
<EventizerProvider bus={eventBus}>
<YourApp />
</EventizerProvider>
);
};
3. Subscribe to events
// UserProfile.tsx
import React, { useState } from 'react';
import { useSubscribe } from 'react-eventizer';
const UserProfile: React.FC = () => {
const [username, setUsername] = useState<string>('');
// Subscribe to the user:login event
useSubscribe('user:login', (payload) => {
setUsername(payload.username);
});
return (
<div>
{username ? `Welcome, ${username}!` : 'Please log in'}
</div>
);
};
4. Emit events
// LoginForm.tsx
import React, { useState } from 'react';
import { useEmitter } from 'react-eventizer';
const LoginForm: React.FC = () => {
const [username, setUsername] = useState('');
const emitLogin = useEmitter('user:login');
const handleLogin = () => {
// Emit the user:login event with payload
emitLogin({ username, id: 123 });
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleLogin(); }}>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<button type="submit">Login</button>
</form>
);
};
API Reference
Core
Eventizer<EM>
The main event bus class.
const eventBus = new Eventizer<EventMap>();
Methods:
on<K>(event: K, callback: (payload: EM[K]) => void): () => void
- Subscribe to an eventoff<K>(event: K, callback: (payload: EM[K]) => void): void
- Unsubscribe from an eventemit<K>(event: K, payload: EM[K]): void
- Emit an event with payloadsubscriberCount<K>(event: K): number
- Get the number of subscribers for an eventclearEvent<K>(event: K): void
- Remove all subscribers for an eventclearAll(): void
- Remove all subscribers for all events
React Integration
EventizerProvider
React context provider for the event bus.
<EventizerProvider bus={eventBus}>
{children}
</EventizerProvider>
useEventizer()
Hook to access the event bus instance.
const eventBus = useEventizer();
useSubscribe<K>(event: K, callback: (payload: EventMap[K]) => void, deps?: any[])
Hook to subscribe to an event and automatically unsubscribe on component unmount.
useSubscribe('user:login', (payload) => {
console.log(`User logged in: ${payload.username}`);
});
useEmitter<K>(event: K): (payload: EventMap[K]) => void
Hook to create an event emitter function.
const emitLogin = useEmitter('user:login');
// Later...
emitLogin({ username: 'john', id: 123 });
When to Use an Event Bus vs. State Management
While state management libraries like Redux, Zustand, or Context API are powerful tools for managing application state, an event bus offers distinct advantages in certain scenarios. Here are situations where react-eventizer shines:
1. Cross-Component Communication Without Prop Drilling
Problem: Components need to communicate across different parts of the component tree without direct parent-child relationships.
Solution: An event bus allows any component to emit events that can be received by any other component, regardless of their position in the component tree.
// In a deeply nested component
const DeleteButton = () => {
const emitDelete = useEmitter('item:delete');
return <button onClick={() => emitDelete(itemId)}>Delete</button>;
};
// In a completely different part of the app
const Notifications = () => {
useSubscribe('item:delete', (itemId) => {
showNotification(`Item ${itemId} deleted successfully`);
});
// ...
};
2. Decoupled Component Architecture
Problem: Tightly coupled components make code harder to maintain and test.
Solution: An event bus promotes loose coupling by allowing components to communicate without direct dependencies.
3. Notification and Alert Systems
Problem: Notifications need to be triggered from anywhere in the app but displayed in a central component.
Solution: Components can emit notification events that are handled by a central notification manager.
// Any component can trigger a notification
const saveData = async () => {
try {
await api.save(data);
emitNotification({ type: 'success', message: 'Data saved successfully' });
} catch (error) {
emitNotification({ type: 'error', message: 'Failed to save data' });
}
};
// Notification component listens for all notifications
const NotificationCenter = () => {
const [notifications, setNotifications] = useState([]);
useSubscribe('notification:new', (notification) => {
setNotifications(prev => [...prev, notification]);
});
// Render notifications...
};
4. Global UI State Changes
Problem: UI changes like theme switching or sidebar toggling need to affect multiple components.
Solution: Emit a single event that all interested components can subscribe to.
5. Handling Asynchronous Events
Problem: Managing asynchronous events like WebSocket messages or long-polling updates.
Solution: Emit events when async data arrives, allowing any component to react accordingly.
// WebSocket service
socket.onMessage((data) => {
eventBus.emit('socket:message', data);
});
// Any component can listen
const LiveUpdates = () => {
useSubscribe('socket:message', (data) => {
// Update component based on socket data
});
// ...
};
6. When to Stick with State Management
While an event bus is powerful, traditional state management might be better when:
- You need to persist and access state across the entire application
- You require time-travel debugging or state snapshots
- Your application has complex state transitions and validations
- You need middleware for side effects (though you can build this with an event bus too)
Advanced Usage
Custom Event Maps
You can extend the base EventMap
interface to add your own events:
import { EventMap as BaseEventMap } from 'react-eventizer';
export interface EventMap extends BaseEventMap {
'cart:add': { productId: string; quantity: number };
'cart:remove': { productId: string };
'cart:clear': void;
}
Using with Multiple Event Buses
For more complex applications, you might want to use multiple event buses:
// Create specialized event buses
const userEventBus = new Eventizer<UserEventMap>();
const uiEventBus = new Eventizer<UIEventMap>();
// Provide them at different levels of your component tree
<EventizerProvider bus={userEventBus}>
<UserRelatedComponents />
<EventizerProvider bus={uiEventBus}>
<UIComponents />
</EventizerProvider>
</EventizerProvider>
Best Practices
- Define Event Types: Always define your event types in a central location for consistency.
- Use Namespaces: Prefix your events with namespaces (e.g.,
user:
,ui:
) to avoid collisions. - Cleanup: The
useSubscribe
hook handles cleanup automatically, but if you useon()
directly, remember to unsubscribe. - Performance: Avoid emitting events in tight loops or render functions.
License
MIT
5 months ago