From a0b2e27f6e81f065431af18802828bfb479e89fe Mon Sep 17 00:00:00 2001 From: cheton Date: Fri, 13 Oct 2023 23:14:36 +0800 Subject: [PATCH] feat: refine `usePortalManager` and `useToastManager` Hooks to avoid unnecessary re-renders --- packages/react/src/portal/usePortalManager.js | 20 ++++++++++++------- packages/react/src/toast/useToastManager.js | 6 +++--- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/react/src/portal/usePortalManager.js b/packages/react/src/portal/usePortalManager.js index 2388c6a961..c22e2de1a9 100644 --- a/packages/react/src/portal/usePortalManager.js +++ b/packages/react/src/portal/usePortalManager.js @@ -1,7 +1,10 @@ -import { useContext, useMemo } from 'react'; +import { useContext, useRef } from 'react'; import { PortalManagerContext } from './context'; const usePortalManager = () => { + const createPortalRef = useRef(null); + const portalManagerRef = useRef(null); + if (!useContext) { throw new Error('The `useContext` hook is not available with your React version.'); } @@ -12,14 +15,17 @@ const usePortalManager = () => { throw new Error('The `usePortalManager` hook must be called from a descendent of the `PortalManager`.'); } - const portal = useMemo(() => { - const fn = function (...args) { - return context.add(...args); + createPortalRef.current = context.add; + + if (!portalManagerRef.current) { + portalManagerRef.current = function (...args) { + return createPortalRef.current?.(...args); }; - return Object.assign(fn, context); - }, [context]); + } + + portalManagerRef.current = Object.assign(portalManagerRef.current, context); - return portal; + return portalManagerRef.current; }; export default usePortalManager; diff --git a/packages/react/src/toast/useToastManager.js b/packages/react/src/toast/useToastManager.js index 0bf1244d9d..4fbcedbbc3 100644 --- a/packages/react/src/toast/useToastManager.js +++ b/packages/react/src/toast/useToastManager.js @@ -2,8 +2,8 @@ import { useContext, useRef } from 'react'; import { ToastManagerContext } from './context'; const useToastManager = () => { + const createToastRef = useRef(null); const toastManagerRef = useRef(null); - const notifyRef = useRef(null); if (!useContext) { throw new Error('The `useContext` hook is not available with your React version.'); @@ -15,11 +15,11 @@ const useToastManager = () => { throw new Error('The `useToastManager` hook must be called from a descendent of the `ToastManager`.'); } - notifyRef.current = context.notify; + createToastRef.current = context.notify; if (!toastManagerRef.current) { toastManagerRef.current = function (...args) { - return notifyRef.current?.(...args); + return createToastRef.current?.(...args); }; }