Global event bus hook for react
npm install --save react-gbus
- 📢 Broadcast(emit) from anywhere (not limited to react components)
- 🍃 Ultra lightweight less then 1KB
- ✌ Written w/ TypeScript
import React, { useState } from "react";
import BusProvider, { useListener, emit } from "react-gbus";
const FRUIT_CHANGE = "fch";
function FruitViewer() {
const [Fruit, setFruit] = useState("Choose your Fruit");
useListener(setFruit, [FRUIT_CHANGE]);
return <h1>{Fruit}</h1>;
}
const FruitChooser = () => (
<div>
<button onClick={() => emit(FRUIT_CHANGE, "🍎")}>Apple</button>
<button onClick={() => emit(FRUIT_CHANGE, "🥭")}>Mango</button>
<button onClick={() => emit(FRUIT_CHANGE, "🍍")}>Pineapple</button>
</div>
);
const App = () => (
<BusProvider>
<FruitViewer />
<FruitChooser />
</BusProvider>
);
MIT © harshzalavadiya