题意:为什么我的组件即使自定义 Hook 的值没有变化也在重新渲染?
问题背景:
I'm working with nested custom hooks in React, and I'm experiencing an unexpected re-render in my parent component, even though the value returned from one of the custom hooks remains unchanged. Specifically, the useIsAdmin hook depends on the session data from useSession, but even when the session's roles don't change, the parent component re-renders.
我正在使用 React 中嵌套的自定义 Hook,尽管其中一个自定义 Hook 返回的值没有改变,但我的父组件出现了意外的重新渲染。具体来说,`useIsAdmin` 依赖于 `useSession` 的会话数据,但即使会话的角色没有变化,父组件仍然会重新渲染。
Here’s a simplified version of my code:
这是我的代码的简化版本:
// Custom hook to check if user is admin
export const useIsAdmin = () => {
const { data: session } = useSession(); // Fetch session data
// Check if the user's roles match the required admin roles
return useMemo(
() =>
ADMIN_READ.every((role) =>
session?.roles?.find((userRole) => userRole === role)
),
[session?.roles]
);
};
Issue: 问题:
The useIsAdmin hook is the middle custom hook. Each time useSession fetches the session, even though the session.roles value remains the same, the parent component still re-renders. I expected the useMemo to prevent re-renders as long as session.roles hasn’t changed.
`useIsAdmin` Hook 是中间的自定义 Hook。每次 `useSession` 获取会话时,即使 `session.roles` 的值保持不变,父组件仍然会重新渲染。我原本期望 `useMemo` 能够防止重新渲染,只要 `session.roles` 没有改变。
What I’ve tried: 我尝试过的:
- I've checked if the roles are deeply equal but the re-render happens regardless. 我检查过角色是否深度相等,但无论如何都会发生重新渲染。
- Tried using React.memo for the parent component to prevent unnecessary re-renders, but it still occurs. 尝试使用 `React.memo` 来防止父组件不必要的重新渲染,但仍然会发生。
- Verified that session.roles remains identical between renders. 验证了 `session.roles` 在渲染之间保持不变。
Question: 问题:
Why is the parent component re-rendering even though useIsAdmin's result doesn't change when session.roles is the same? Is there a problem with how I’m using useSession or useMemo in this nested hook setup?
为什么即使 `session.roles` 相同,`useIsAdmin` 的结果没有变化,父组件仍然会重新渲染?我在这个嵌套 Hook 设置中使用 `useSession` 或 `useMemo` 的方式是否存在问题?
Additional Info: 附加信息:
- I'm using React v18.3.1 我正在使用 React v18.3.1。
- The parent component re-renders whenever useSession fetches data, despite session.roles being unchanged. 每当 `useSession` 获取数据时,父组件都会重新渲染,尽管 `session.roles` 没有改变。
Want to prevent the component rerendering whenever last child custom hook return same data
希望防止组件在最后一个子自定义 Hook 返回相同数据时重新渲染。
问题解决:
I've checked if the roles are deeply equal but the re-render happens regardless.
React renders when the state changes reference. Deep equality isn't important here; if you're creating a new array with the same values, that will trigger a re-render.
当状态更改引用时,React 会重新渲染。在这里,深度相等并不重要;如果你创建一个包含相同值的新数组,这将触发重新渲染。
It would help to see what your useSession
hook looks like.
查看你的 `useSession` Hook 是什么样的会很有帮助。