Skip to content

Commit

Permalink
fix(blade): fallback for useInsertionEffect (#2450)
Browse files Browse the repository at this point in the history
* fix(blade): fallback for useInsertionEffect

* chore: prevent webpack from analyzing useInsertionEffect

* Create fair-beers-confess.md
  • Loading branch information
anuraghazra authored Dec 26, 2024
1 parent 2da77e4 commit 95a5824
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/fair-beers-confess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@razorpay/blade": patch
---

fix(blade): Add backwards compat for React17 - fallback for useInsertionEffect
16 changes: 11 additions & 5 deletions packages/blade/src/utils/useCallbackRef.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -11,11 +19,9 @@ function useCallbackRef<Args extends unknown[], Return>(
callback: ((...args: Args) => Return) | undefined,
deps: React.DependencyList = [],
) {
const callbackRef = useRef<typeof callback>(() => {
throw new Error('Cannot call an event handler while rendering.');
});
const callbackRef = useRef<typeof callback>(callback);

useInsertionEffect(() => {
useInsertionEffectFallback(() => {
callbackRef.current = callback;
});

Expand Down

0 comments on commit 95a5824

Please sign in to comment.