perf(frontend): Context value useMemo 稳定化
AuthContext.Provider 和 ToastContext.Provider 的 value 对象 用 useMemo 包裹,避免每次 Provider render 产生新引用导致 所有消费者不必要的 re-render。
This commit is contained in:
@ -3,6 +3,7 @@ import {
|
|||||||
useContext,
|
useContext,
|
||||||
useState,
|
useState,
|
||||||
useCallback,
|
useCallback,
|
||||||
|
useMemo,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { X, CheckCircle, AlertCircle, Info } from "lucide-react";
|
import { X, CheckCircle, AlertCircle, Info } from "lucide-react";
|
||||||
@ -52,8 +53,11 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
|||||||
}, 3500);
|
}, 3500);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 🚀 稳定 Context value 引用
|
||||||
|
const ctxValue = useMemo<ToastContextValue>(() => ({ toast }), [toast]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ToastContext.Provider value={{ toast }}>
|
<ToastContext.Provider value={ctxValue}>
|
||||||
{children}
|
{children}
|
||||||
|
|
||||||
{/* Toast 渲染区 */}
|
{/* Toast 渲染区 */}
|
||||||
|
|||||||
@ -3,6 +3,7 @@ import {
|
|||||||
useContext,
|
useContext,
|
||||||
useState,
|
useState,
|
||||||
useCallback,
|
useCallback,
|
||||||
|
useMemo,
|
||||||
useEffect,
|
useEffect,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
@ -107,15 +108,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
logoutInternal();
|
logoutInternal();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 🚀 稳定 Context value 引用,避免消费者不必要的 re-render
|
||||||
|
const ctxValue = useMemo<AuthContextValue>(
|
||||||
|
() => ({
|
||||||
|
...state,
|
||||||
|
login,
|
||||||
|
logout,
|
||||||
|
isAuthenticated: !!state.token && !!state.user,
|
||||||
|
}),
|
||||||
|
[state, login, logout],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider value={ctxValue}>
|
||||||
value={{
|
|
||||||
...state,
|
|
||||||
login,
|
|
||||||
logout,
|
|
||||||
isAuthenticated: !!state.token && !!state.user,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
</AuthContext.Provider>
|
</AuthContext.Provider>
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user