Skip to content

Commit

Permalink
feat: refine usePortalManager and useToastManager Hooks to avoid …
Browse files Browse the repository at this point in the history
…unnecessary re-renders
  • Loading branch information
cheton committed Oct 13, 2023
1 parent 2aff9cf commit a0b2e27
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
20 changes: 13 additions & 7 deletions packages/react/src/portal/usePortalManager.js
Original file line number Diff line number Diff line change
@@ -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.');
}
Expand All @@ -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;
6 changes: 3 additions & 3 deletions packages/react/src/toast/useToastManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand All @@ -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);
};
}

Expand Down

0 comments on commit a0b2e27

Please sign in to comment.