docusaurus/packages/docusaurus-theme-common/src/utils/useLocationChange.ts
Joshua Chen 948271a0ff
test: improve test coverage; reorder theme-common files (#6956)
* test: improve test coverage; reorder theme-common files

* no need for this
2022-03-22 15:33:55 +08:00

38 lines
1 KiB
TypeScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 {useLocation} from '@docusaurus/router';
import type {Location} from 'history';
import {useDynamicCallback, usePrevious} from './reactUtils';
type LocationChangeEvent = {
location: Location;
previousLocation: Location | undefined;
};
type OnLocationChange = (locationChangeEvent: LocationChangeEvent) => void;
export function useLocationChange(onLocationChange: OnLocationChange): void {
const location = useLocation();
const previousLocation = usePrevious(location);
const onLocationChangeDynamic = useDynamicCallback(onLocationChange);
useEffect(() => {
if (!previousLocation) {
return;
}
if (location !== previousLocation) {
onLocationChangeDynamic({
location,
previousLocation,
});
}
}, [onLocationChangeDynamic, location, previousLocation]);
}