Skip to content

Commit 116fced

Browse files
committed
refactor: use Object.assign to avoid unnecessary re-renders
1 parent 5cf5683 commit 116fced

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

src/use-swr-infinite.ts

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { useContext, useRef, useState, useEffect, useCallback } from 'react'
1+
import {
2+
useContext,
3+
useRef,
4+
useState,
5+
useMemo,
6+
useEffect,
7+
useCallback
8+
} from 'react'
29

310
import defaultConfig, { cache } from './config'
411
import SWRConfigContext from './swr-config-context'
@@ -184,6 +191,8 @@ function useSWRInfinite<Data = any, Error = any>(
184191
dataRef.current = swr.data
185192
}, [swr.data])
186193

194+
const boundMutate = useMemo(() => swr.mutate, [swr])
195+
187196
const mutate = useCallback(
188197
(data, shouldRevalidate = true) => {
189198
if (shouldRevalidate && typeof data !== 'undefined') {
@@ -195,9 +204,9 @@ function useSWRInfinite<Data = any, Error = any>(
195204
cache.set(contextCacheKey, { force: true })
196205
}
197206

198-
return swr.mutate(data, shouldRevalidate)
207+
return boundMutate(data, shouldRevalidate)
199208
},
200-
[swr.mutate, contextCacheKey]
209+
[boundMutate, contextCacheKey]
201210
)
202211

203212
// extend the SWR API
@@ -217,23 +226,11 @@ function useSWRInfinite<Data = any, Error = any>(
217226
)
218227

219228
// Use getter functions to avoid unnecessary re-renders caused by triggering all the getters of the returned swr object
220-
return {
221-
get error() {
222-
return swr.error
223-
},
224-
get data() {
225-
return swr.data
226-
},
227-
get revalidate() {
228-
return swr.revalidate
229-
},
230-
get isValidating() {
231-
return swr.isValidating
232-
},
229+
return Object.assign(swr, {
233230
mutate,
234231
size,
235232
setSize
236-
} as SWRInfiniteResponseInterface<Data, Error>
233+
}) as SWRInfiniteResponseInterface<Data, Error>
237234
}
238235

239236
export {

0 commit comments

Comments
 (0)