perf(CollectionHistoryProvider): optimize location context

This commit is contained in:
Zeke Zhang 2024-11-03 17:57:32 +08:00
parent d7a80d0ad6
commit d786145fc2
2 changed files with 23 additions and 5 deletions

View File

@ -11,8 +11,22 @@ import React, { FC, useEffect } from 'react';
import { Location, NavigateFunction, NavigateOptions, useLocation, useNavigate } from 'react-router-dom';
const NavigateNoUpdateContext = React.createContext<NavigateFunction>(null);
NavigateNoUpdateContext.displayName = 'NavigateNoUpdateContext';
const LocationNoUpdateContext = React.createContext<Location>(null);
LocationNoUpdateContext.displayName = 'LocationNoUpdateContext';
export const LocationSearchContext = React.createContext<string>('');
LocationSearchContext.displayName = 'LocationSearchContext';
const IsAdminPageContext = React.createContext<boolean>(false);
IsAdminPageContext.displayName = 'IsAdminPageContext';
const IsAdminPageProvider: FC = ({ children }) => {
const location = useLocation();
const isAdminPage = location.pathname.startsWith('/admin');
return <IsAdminPageContext.Provider value={isAdminPage}>{children}</IsAdminPageContext.Provider>;
};
/**
* When the URL changes, components that use `useNavigate` will re-render.
@ -78,11 +92,17 @@ export const useLocationSearch = () => {
return React.useContext(LocationSearchContext);
};
export const useIsAdminPage = () => {
return React.useContext(IsAdminPageContext);
};
export const CustomRouterContextProvider: FC = ({ children }) => {
return (
<NavigateNoUpdateProvider>
<LocationNoUpdateProvider>
<IsAdminPageProvider>
<LocationSearchProvider>{children}</LocationSearchProvider>
</IsAdminPageProvider>
</LocationNoUpdateProvider>
</NavigateNoUpdateProvider>
);

View File

@ -8,8 +8,8 @@
*/
import React, { createContext, useCallback, useContext, useMemo } from 'react';
import { useLocation } from 'react-router-dom';
import { useAPIClient, useRequest } from '../api-client';
import { useIsAdminPage } from '../application/CustomRouterContextProvider';
import { useAppSpin } from '../application/hooks/useAppSpin';
export interface CollectionHistoryContextValue {
@ -38,9 +38,7 @@ const options = {
export const CollectionHistoryProvider: React.FC = (props) => {
const api = useAPIClient();
const location = useLocation();
const isAdminPage = location.pathname.startsWith('/admin');
const isAdminPage = useIsAdminPage();
const token = api.auth.getToken() || '';
const { render } = useAppSpin();