Skip to content
Closed
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {useEffect} from 'react';
import {useEvent, useShallowMemoObject} from '../utils/reactUtils';
import {useEffect, useMemo} from 'react';
import {
useEvent,
useShallowMemoObject,
useShallowMemoArray,
} from '../utils/reactUtils';

type Options = MutationObserverInit;

Expand All @@ -23,10 +27,21 @@ export function useMutationObserver(
): void {
const stableCallback = useEvent(callback);

// MutationObserver options are not nested much
// so this should be to memo options in 99%
// TODO handle options.attributeFilter array
const stableOptions: Options = useShallowMemoObject(options);
// Memoize attributeFilter array separately for proper deep comparison
const stableAttributeFilter = useShallowMemoArray(options.attributeFilter);

// Memoize remaining options (shallow comparison is fine for booleans)
const {attributeFilter: _, ...restOptions} = options;
const stableRestOptions = useShallowMemoObject(restOptions);

// Combine memoized parts
const stableOptions: Options = useMemo(
() =>
stableAttributeFilter
? {...stableRestOptions, attributeFilter: stableAttributeFilter}
: stableRestOptions,
[stableRestOptions, stableAttributeFilter],
);

useEffect(() => {
const observer = new MutationObserver(stableCallback);
Expand Down
11 changes: 11 additions & 0 deletions packages/docusaurus-theme-common/src/utils/reactUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ export function useShallowMemoObject<O extends object>(obj: O): O {
return useMemo(() => obj, deps.flat());
}

/**
* Shallow-memoize an array. Returns the same array reference if elements
* are shallowly equal to the previous render.
*
* @param arr
*/
export function useShallowMemoArray<T>(arr: T[] | undefined): T[] | undefined {
// eslint-disable-next-line react-compiler/react-compiler,react-hooks/exhaustive-deps
return useMemo(() => arr, arr ?? []);
}

type SimpleProvider = ComponentType<{children: ReactNode}>;

/**
Expand Down
Loading