diff --git a/src/mantine-utils/src/create-use-external-events/create-use-external-events.ts b/src/mantine-utils/src/create-use-external-events/create-use-external-events.ts index ff59863f6b7..36de645d084 100644 --- a/src/mantine-utils/src/create-use-external-events/create-use-external-events.ts +++ b/src/mantine-utils/src/create-use-external-events/create-use-external-events.ts @@ -1,9 +1,11 @@ -import { useEffect, useMemo } from 'react'; +import { useEffect, useLayoutEffect } from 'react'; function dispatchEvent(type: string, detail?: T) { window.dispatchEvent(new CustomEvent(type, { detail })); } +const useIsomorphicEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect; + export function createUseExternalEvents void>>( prefix: string ) { @@ -13,22 +15,17 @@ export function createUseExternalEvents { - if (typeof window !== 'undefined') { + useIsomorphicEffect(() => { + Object.keys(handlers).forEach((eventKey) => { + window.removeEventListener(eventKey, handlers[eventKey]); + window.addEventListener(eventKey, handlers[eventKey]); + }); + + return () => Object.keys(handlers).forEach((eventKey) => { window.removeEventListener(eventKey, handlers[eventKey]); - window.addEventListener(eventKey, handlers[eventKey]); }); - } }, []); - - useEffect( - () => () => - Object.keys(handlers).forEach((eventKey) => { - window.removeEventListener(eventKey, handlers[eventKey]); - }), - [] - ); } function createEvent(event: EventKey) {