Unnecessary Renders Triggered by a Hook after Migrating to Zustand
lcopilot opened this issue · comments
Aurora commented
Subject:
Unnecessary Renders Triggered by a Hook after Migrating to Zustand
Description:
I'm currently in the process of migrating from Redux to Zustand, and I'm facing an issue with a specific hook that triggers unnecessary renders. To ensure a smoother transition and optimize performance, I'm seeking guidance on how to migrate this hook while avoiding the problem of unnecessary renders.
Hooks before migration
import { createSelector } from '@reduxjs/toolkit';
import { stateSelector } from 'app/store/store';
import { useAppSelector } from 'app/store/storeHooks';
import { defaultSelectorOptions } from 'app/store/util/defaultMemoizeOptions';
import { useMemo } from 'react';
export const useNames = (nodeId: string) => {
const selector = useMemo(
() =>
createSelector(
stateSelector,
({ state }) => {
// This has undergone complex calculations and relevant omissions have been made for code safety
return 11
},
defaultSelectorOptions
),
[nodeId]
);
const names = useAppSelector(selector);
return names;
};
// app/store/util/defaultMemoizeOptions.ts
import { isEqual } from 'lodash-es';
export const defaultSelectorOptions = {
memoizeOptions: {
resultEqualityCheck: isEqual,
},
};
Results after migration
import { useMemo } from 'react'
import useFlowStore from '@/store/flow/useFlow'
export const useNames = (nodeId: string) => {
const nodes=useFlowStore(state=>state.nodes)
const nodeTemplates=useFlowStore(state=>state.nodeTemplates)
const names = useMemo(() => {
// This has undergone complex calculations and relevant omissions have been made for code safety
// Used nodeTemplates and nodes
return 11
}, [nodeId, nodeTemplates, nodes])
return names
}