-
The docs state
How? I fail to understand, how the object destruct (which happens outside the realm of the useSwr hook) leads to less re-renders? So how does this magic work - javascript wise? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
With same question, I saw the source code, realizing SWR is really amazing! The answer is
The most magic thing is how to detect accessed states (btw, before seeing the code, I thought only babel could make it): return {
mutate: boundMutate,
get data() {
stateDependencies.data = true
return data
},
get error() {
stateDependencies.error = true
return error
},
get isValidating() {
stateDependencies.isValidating = true
return isValidating
}
} as SWRResponse<Data, Error> As long as we access Ref: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get I think we can do more interesting things after knowing it 😄 |
Beta Was this translation helpful? Give feedback.
With same question, I saw the source code, realizing SWR is really amazing!
The answer is
use-swr.ts
andutils/state.ts
.useStateWithDeps
inutils/state.ts
export[stateRef, stateDependenciesRef, setState]
. When we setState, it will not rerender directly. However, it checks the stateDependenciesRef, and only rerenders when accessed states change.The most magic thing is how to detect accessed states (btw, before seeing the code, I thought only babel could make it):
Just see the code: the object that useSWR return is: