Skip to content

Commit ff658ee

Browse files
committed
chore: refactor useMutationState, fix tests
1 parent 4f00031 commit ff658ee

File tree

2 files changed

+19
-13
lines changed

2 files changed

+19
-13
lines changed

packages/react-query/src/__tests__/useMutationState.test.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,15 @@ describe('useIsMutating', () => {
6666
const isMutatings: Array<number> = []
6767
const queryClient = createQueryClient()
6868

69-
function IsMutating() {
69+
function IsMutatingBase() {
7070
const isMutating = useIsMutating({ mutationKey: ['mutation1'] })
7171
isMutatings.push(isMutating)
7272
return null
7373
}
7474

75+
// Memo to avoid other `useMutation` hook causing a re-render
76+
const IsMutating = React.memo(IsMutatingBase)
77+
7578
function Page() {
7679
const { mutate: mutate1 } = useMutation({
7780
mutationKey: ['mutation1'],
@@ -104,7 +107,7 @@ describe('useIsMutating', () => {
104107
const isMutatings: Array<number> = []
105108
const queryClient = createQueryClient()
106109

107-
function IsMutating() {
110+
function IsMutatingBase() {
108111
const isMutating = useIsMutating({
109112
predicate: (mutation) =>
110113
mutation.options.mutationKey?.[0] === 'mutation1',
@@ -113,6 +116,8 @@ describe('useIsMutating', () => {
113116
return null
114117
}
115118

119+
const IsMutating = React.memo(IsMutatingBase);
120+
116121
function Page() {
117122
const { mutate: mutate1 } = useMutation({
118123
mutationKey: ['mutation1'],

packages/react-query/src/useMutationState.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,19 +64,20 @@ export function useMutationState<TResult = MutationState>(
6464
return React.useSyncExternalStore(
6565
React.useCallback(
6666
(onStoreChange) =>
67-
mutationCache.subscribe(() => {
68-
const nextResult = replaceEqualDeep(
69-
result.current,
70-
getResult(mutationCache, optionsRef.current),
71-
)
72-
if (result.current !== nextResult) {
73-
result.current = nextResult
74-
notifyManager.schedule(onStoreChange)
75-
}
76-
}),
67+
mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),
7768
[mutationCache],
7869
),
79-
() => result.current,
70+
() => {
71+
const nextResult = replaceEqualDeep(
72+
result.current,
73+
getResult(mutationCache, optionsRef.current),
74+
)
75+
if (result.current !== nextResult) {
76+
result.current = nextResult
77+
}
78+
79+
return result.current
80+
},
8081
() => result.current,
8182
)!
8283
}

0 commit comments

Comments
 (0)