From 9f5217d3398d083a44f3bf86f0e4544bb95dc76d Mon Sep 17 00:00:00 2001 From: anuraghazra Date: Thu, 2 Jan 2025 13:37:12 +0530 Subject: [PATCH] fix: backward compat with react17 --- packages/blade/src/utils/useCallbackRef.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/blade/src/utils/useCallbackRef.ts b/packages/blade/src/utils/useCallbackRef.ts index ce6f05c2630..446c8a9d126 100644 --- a/packages/blade/src/utils/useCallbackRef.ts +++ b/packages/blade/src/utils/useCallbackRef.ts @@ -1,5 +1,13 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/explicit-function-return-type */ -import { useCallback, useInsertionEffect, useRef } from 'react'; +import React, { useCallback, useRef } from 'react'; +import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'; + +// Prevent webpack from importing this: +// https://github.com/webpack/webpack/issues/14814#issuecomment-1536757985 +// https://github.com/radix-ui/primitives/issues/2796 +const useReactInsertionEffect = (React as any)[' useInsertionEffect '.trim().toString()]; +const useInsertionEffectFallback = useReactInsertionEffect || useIsomorphicLayoutEffect; /** * This hook is user-land implementation of the experimental `useEffectEvent` hook. @@ -11,11 +19,9 @@ function useCallbackRef( callback: ((...args: Args) => Return) | undefined, deps: React.DependencyList = [], ) { - const callbackRef = useRef(() => { - throw new Error('Cannot call an event handler while rendering.'); - }); + const callbackRef = useRef(callback); - useInsertionEffect(() => { + useInsertionEffectFallback(() => { callbackRef.current = callback; });