Coding task · JavaScript and React course · Module 15: Patterns and Architecture

Practice: EventBus and useEventListener

The publisher announces what happened and the subscriber reacts, and neither imports the other. The function returned from useEffect is the cleanup: React calls it on unmount, and in StrictMode also between the double run of the effect, so without it listeners would pile up. The listener calls savedHandler.current, so it always uses the latest version of the handler, and the subscription is renewed only when the event name changes. Optional chaining (?.) protects against an event nobody listens to.

Task

Finish the event bus and the hooks through which two independent components talk. ___BLANK1___: the function returned by on removes only this one callback from the listeners of the event. ___BLANK2___: emit calls every listener with the payload data. ___BLANK3___: in useEffect subscribe the listener to eventBus and return the unsubscribe function as the effect cleanup. ___BLANK4___: on a click EnginePanel emits the engine:speedChanged event with the object { speed }, and SpeedDisplay shows the received speed.