Skip to content

Commit 35673e4

Browse files
author
nebarf
committed
Bus subscription: switch to layout effetch to perform event subscriptions
1 parent 7b9990e commit 35673e4

File tree

1 file changed

+2
-18
lines changed

1 file changed

+2
-18
lines changed

src/events-manager/use-bus-subscribe.ts

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { useCompareEffect } from '../shared';
21
import { useRef, useCallback } from 'react';
32
import fastCompare from 'react-fast-compare';
43
import { HttpEventClassType, HttpEventHandler } from './types';
54
import { useEventBus } from './event-bus-context';
5+
import { useCompareLayoutEffect } from '../shared/use-compare-layout-effect';
66

77
export const useBusSubscribe = <T>(
88
eventName: HttpEventClassType<T>,
@@ -15,18 +15,6 @@ export const useBusSubscribe = <T>(
1515
// registering the same event handler multiple times.
1616
const unsubscribeRef = useRef<() => void>();
1717

18-
// Keeps track of the first run of the hook and the related subscription.
19-
const firstRunRef = useRef(true);
20-
const unsubcribeFirstRunRef = useRef<() => void>();
21-
22-
// Subscribe to the event on first hook run. "useEffect" hook will first
23-
// run after component rendering, if child components cause http events to
24-
// be triggered they want be receveived from this subscriber.
25-
if (firstRunRef.current) {
26-
unsubcribeFirstRunRef.current = eventBus.subscribe(eventName, handler);
27-
firstRunRef.current = false;
28-
}
29-
3018
/**
3119
* Detach the handler for the event.
3220
*/
@@ -40,12 +28,8 @@ export const useBusSubscribe = <T>(
4028
/**
4129
* Setup the event handler.
4230
*/
43-
useCompareEffect(
31+
useCompareLayoutEffect(
4432
() => {
45-
if (unsubcribeFirstRunRef.current) {
46-
unsubcribeFirstRunRef.current();
47-
unsubcribeFirstRunRef.current = undefined;
48-
}
4933
// Subscribe to the event and keep track of the subscription.
5034
unsubscribeRef.current = eventBus.subscribe(eventName, handler);
5135

0 commit comments

Comments
 (0)