Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core] fix(HotkeysProvider): memoize context value #6652

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/core/src/context/hotkeys/hotkeysProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type HotkeysAction =
| { type: "ADD_HOTKEYS" | "REMOVE_HOTKEYS"; payload: HotkeyConfig[] }
| { type: "CLOSE_DIALOG" | "OPEN_DIALOG" };

export type HotkeysContextInstance = [HotkeysContextState, React.Dispatch<HotkeysAction>];
export type HotkeysContextInstance = readonly [HotkeysContextState, React.Dispatch<HotkeysAction>];

const initialHotkeysState: HotkeysContextState = { hasProvider: false, hotkeys: [], isDialogOpen: false };
const noOpDispatch: React.Dispatch<HotkeysAction> = () => null;
Expand Down Expand Up @@ -111,6 +111,8 @@ export const HotkeysProvider = ({ children, dialogProps, renderDialog, value }:
const hasExistingContext = value != null;
const fallbackReducer = React.useReducer(hotkeysReducer, { ...initialHotkeysState, hasProvider: true });
const [state, dispatch] = value ?? fallbackReducer;
// The `useState` array isn't stable between renders -- so memo it outselves
const contextValue = React.useMemo(() => [state, dispatch] as const, [state, dispatch]);
const handleDialogClose = React.useCallback(() => dispatch({ type: "CLOSE_DIALOG" }), [dispatch]);

const dialog = renderDialog?.(state, { handleDialogClose }) ?? (
Expand All @@ -124,7 +126,7 @@ export const HotkeysProvider = ({ children, dialogProps, renderDialog, value }:

// if we are working with an existing context, we don't need to generate our own dialog
return (
<HotkeysContext.Provider value={[state, dispatch]}>
<HotkeysContext.Provider value={contextValue}>
{children}
{hasExistingContext ? undefined : dialog}
</HotkeysContext.Provider>
Expand Down