Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

render-optimizations.md

93 lines4.7 KB

1---
2id: render-optimizations
3title: Render Optimizations
4---
5​
6React Query applies a couple of optimizations automatically to ensure that your components only re-render when they actually need to. This is done by the following means:
7​
8## structural sharing
9​
10React Query uses a technique called "structural sharing" to ensure that as many references as possible will be kept intact between re-renders. If data is fetched over the network, usually, you'll get a completely new reference by json parsing the response. However, React Query will keep the original reference if _nothing_ changed in the data. If a subset changed, React Query will keep the unchanged parts and only replace the changed parts.
11​
12> Note: This optimization only works if the `queryFn` returns JSON compatible data. You can turn it off by setting `structuralSharing: false` globally or on a per-query basis, or you can implement your own structural sharing by passing a function to it.
13​
14If your data contains custom value types, you can pass an equality function to `replaceEqualDeep` from your `structuralSharing` function. The previous value is kept when the function returns `true`:
15​
16```tsx
17import { replaceEqualDeep, useQuery } from '@tanstack/react-query'
18​
19const equalityFn = (a: unknown, b: unknown) =>
20 a === b ||
21 (a instanceof Date && b instanceof Date && a.getTime() === b.getTime())
22​
23useQuery({
24 queryKey: ['events'],
25 queryFn: fetchEvents,
26 structuralSharing: (oldData, newData) =>
27 replaceEqualDeep(oldData, newData, equalityFn),
28})
29```
30​
31### referential identity
32​
33The top level object returned from `useQuery`, `useInfiniteQuery`, `useMutation` and the Array returned from `useQueries` is **not referentially stable**. It will be a new reference on every render. However, the `data` properties returned from these hooks will be as stable as possible.
34​
35## tracked properties
36​
37React Query will only trigger a re-render if one of the properties returned from `useQuery` is actually "used". This is done by using [Proxy object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). This avoids a lot of unnecessary re-renders, e.g. because properties like `isFetching` or `isStale` might change often, but are not used in the component.
38​
39You can customize this feature by setting `notifyOnChangeProps` manually globally or on a per-query basis. If you want to turn that feature off, you can set `notifyOnChangeProps: 'all'`.
40​
41> Note: The get trap of a proxy is invoked by accessing a property, either via destructuring or by accessing it directly. If you use object rest destructuring, you will disable this optimization. We have a [lint rule](../../../eslint/no-rest-destructuring.md) to guard against this pitfall.
42​
43## select
44​
45You can use the `select` option to select a subset of the data that your component should subscribe to. This is useful for highly optimized data transformations or to avoid unnecessary re-renders.
46​
47```js
48export const useTodos = (select) => {
49 return useQuery({
50 queryKey: ['todos'],
51 queryFn: fetchTodos,
52 select,
53 })
55​
56export const useTodoCount = () => {
57 return useTodos((data) => data.length)
59```
60​
61A component using the `useTodoCount` custom hook will only re-render if the length of the todos changes. It will **not** re-render if e.g. the name of a todo changed.
62​
63> Note: `select` operates on successfully cached data and is not the appropriate place to throw errors. The source of truth for errors is the `queryFn`, and a `select` function that returns an error results in `data` being `undefined` and `isSuccess` being `true`. We recommend handling errors in the `queryFn` if you wish to have a query fail on incorrect data, or outside of the query hook if you have an error case not related to caching.
64​
65### memoization
66​
67The `select` function will only re-run if:
68​
69- the `select` function itself changed referentially
70- `data` changed
71​
72This means that an inlined `select` function, as shown above, will run on every render. To avoid this, you can wrap the `select` function in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies:
73​
74```js
75// wrapped in useCallback
76export const useTodoCount = () => {
77 return useTodos(useCallback((data) => data.length, []))
79```
80​
81```js
82// extracted to a stable function reference
83const selectTodoCount = (data) => data.length
84​
85export const useTodoCount = () => {
86 return useTodos(selectTodoCount)
88```
89​
90## Further Reading
91​
92For an in-depth guide about these topics, read [React Query Render Optimizations](https://tkdodo.eu/blog/react-query-render-optimizations) from
93the TkDodo. To learn how to best optimize the `select` option, read [React Query Selectors, Supercharged](https://tkdodo.eu/blog/react-query-selectors-supercharged)