1.1.0 • Published 11 months ago

mitt-react v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

Mitt React

mitt-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.

In more detail, this package offers a hook that automatically handles event subscription and unsubscription using the 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.

Installation

npm install mitt-react

Usage

useEventListener (hook)

The useEventListener hook allows you to listen to custom events in your React components.

import React, { useState } from 'react';
import { useEventListener } from 'mitt-react';

const MyComponent = () => {
  const [message, setMessage] = useState('');

  useEventListener('customEvent', (data) => {
    setMessage(data);
  });

  return (
    <div>
      <p>{message}</p>
    </div>
  );
};

export default MyComponent;

useEventEmit (function)

The useEventEmit function allows you to emit custom events.

import React from 'react';
import { useEventEmit } from 'mitt-react';

const MyEmitterComponent = () => {
  const handleClick = () => {
    useEventEmit('customEvent', 'Hello, World!');
  };

  return <button onClick={handleClick}>Emit Event</button>;
};

export default MyEmitterComponent;

API

useEventListener

A hook to listen for a custom event.

ParamTypeNullableDesc
eventNamestringThe name of the event to listen for
handlerFunctionThe function to call when the event is emitted.

useEventEmit

A function to emit a custom event.

ParamTypeNullableDesc
eventNamestringThe name of the event to emit.
dataanyThe data to pass to the event handler.

Contribution

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.