Lightweight utility for integrating mitt with React
npm install mitt-reactmitt-react is a lightweight utility for integrating the mitt event emitter with React functional components. It provides hooks for listening to and emitting events in a React-friendly way. useEffect hook. This simplifies the process of managing event listeners in React components, ensuring they are properly set up and cleaned up to avoid memory leaks.
bash
npm install mitt-react
`
Usage
$3
The useEventListener hook allows you to listen to custom events in your React components.
`jsx
import React, { useState } from "react";
import { useEventListener } from "mitt-react";
const MyComponent = () => {
const [message, setMessage] = useState("");
useEventListener("customEvent", (data) => {
setMessage(data);
});
return (
{message}
);
};
export default MyComponent;
`
$3
The eventEmit function allows you to emit custom events.
`jsx
import React from "react";
import { eventEmit } from "mitt-react";
const MyEmitterComponent = () => {
const handleClick = () => {
eventEmit("customEvent", "Hello, World!");
};
return ;
};
export default MyEmitterComponent;
`
API
$3
A hook to listen for a custom event.
| Param | Type | Nullable | Desc |
| --------- | -------- | -------- | ----------------------------------------------- |
| eventName | string | ✗ | The name of the event to listen for |
| handler | Function | ✗ | The function to call when the event is emitted. |
$3
A function to emit a custom event.
| Param | Type | Nullable | Desc |
| --------- | ------ | -------- | -------------------------------------- |
| eventName | string | ✗ | The name of the event to emit. |
| data | any | ✗ | The data to pass to the event handler. |
$3
These types can be imported this way:
`js
import type { EventMap } from "mitt-vue";
`
Here is the list of types used in the package.
`ts
export type EventMap = Record;
export type EventCallback = (...args: any[]) => void;
``