Skip to content

Commit 6bf25a9

Browse files
standytrojanowski
authored andcommitted
perf(useQuery): memoize helper functions (#126)
closes #125
1 parent e54850e commit 6bf25a9

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

src/useQuery.ts

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,16 @@ export function useQuery<
131131

132132
const [responseId, setResponseId] = useState(0);
133133

134-
const currentResult = useMemo<QueryHookState<TData>>(
134+
const currentResult = useMemo<QueryHookResult<TData, TVariables>>(
135135
() => {
136+
const helpers = {
137+
fetchMore: observableQuery.fetchMore.bind(observableQuery),
138+
refetch: observableQuery.refetch.bind(observableQuery),
139+
startPolling: observableQuery.startPolling.bind(observableQuery),
140+
stopPolling: observableQuery.stopPolling.bind(observableQuery),
141+
updateQuery: observableQuery.updateQuery.bind(observableQuery),
142+
};
143+
136144
const result = observableQuery.currentResult();
137145

138146
// return the old result data when there is an error
@@ -144,7 +152,19 @@ export function useQuery<
144152
};
145153
}
146154

155+
if (shouldSkip) {
156+
// Taken from https://github.com/apollographql/react-apollo/blob/5cb63b3625ce5e4a3d3e4ba132eaec2a38ef5d90/src/Query.tsx#L376-L381
157+
return {
158+
...helpers,
159+
data: undefined,
160+
error: undefined,
161+
loading: false,
162+
networkStatus: undefined,
163+
};
164+
}
165+
147166
return {
167+
...helpers,
148168
data,
149169
error:
150170
result.errors && result.errors.length > 0
@@ -193,25 +213,6 @@ export function useQuery<
193213

194214
ensureSupportedFetchPolicy(suspend, fetchPolicy);
195215

196-
const helpers = {
197-
fetchMore: observableQuery.fetchMore.bind(observableQuery),
198-
refetch: observableQuery.refetch.bind(observableQuery),
199-
startPolling: observableQuery.startPolling.bind(observableQuery),
200-
stopPolling: observableQuery.stopPolling.bind(observableQuery),
201-
updateQuery: observableQuery.updateQuery.bind(observableQuery),
202-
};
203-
204-
if (shouldSkip) {
205-
// Taken from https://github.com/apollographql/react-apollo/blob/5cb63b3625ce5e4a3d3e4ba132eaec2a38ef5d90/src/Query.tsx#L376-L381
206-
return {
207-
...helpers,
208-
data: undefined,
209-
error: undefined,
210-
loading: false,
211-
networkStatus: undefined,
212-
};
213-
}
214-
215216
if (currentResult.partial) {
216217
if (suspend) {
217218
// throw a promise - use the react suspense to wait until the data is
@@ -224,7 +225,7 @@ export function useQuery<
224225
}
225226
}
226227

227-
return { ...helpers, ...currentResult };
228+
return currentResult;
228229
}
229230

230231
function ensureSupportedFetchPolicy(

0 commit comments

Comments
 (0)