import React, { useMemo } from "react"; import useSubscription from "./useSubscription"; // In this example, "source" is an event dispatcher (e.g. an HTMLInputElement) // but it could be anything that emits an event and has a readable current value. function Example({ source }) { // In order to avoid removing and re-adding subscriptions each time this hook is called, // the parameters passed to this hook should be memoized. const subscription = useMemo( () => ({ getCurrentValue: () => source.value, subscribe: callback => { source.addEventListener("change", callback); return () => source.removeEventListener("change", callback); } }), // Re-subscribe any time our "source" changes // (e.g. we get a new HTMLInputElement target) [source] ); const value = useSubscription(subscription); // Your rendered output here ... }