Skip to content

Commit f675cd8

Browse files
committed
📝 Expand selectFromResult explanation
1 parent eff7527 commit f675cd8

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

docs/rtk-query/usage/queries.mdx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,34 @@ function PostById({ id }: { id: number }) {
297297
}
298298
```
299299

300+
Note that a shallow equality check is performed on the overall return value of `selectFromResult` to determine whether to force a rerender. i.e. it will trigger a rerender if any of the returned object values change reference. If a new array/object is created and used as a return value within the callback, it will hinder the performance benefits due to being identified as a new item each time the callback is run. When intentionally providing an empty array/object, in order to avoid re-creating it each time the callback runs, you can declare an empty array/object outside of the component in order to maintain a stable reference.
301+
302+
```tsx title="Using selectFromResult with a stable empty array"
303+
// An array declared here will maintain a stable reference rather than be re-created again
304+
const emptyArray: Post[] = []
305+
306+
function PostsList() {
307+
// This call will result in an initial render returning an empty array for `posts`,
308+
// and a second render when the data is received.
309+
// It will trigger additional rerenders only if the `posts` data changes
310+
const { posts } = api.useGetPostsQuery(undefined, {
311+
selectFromResult: ({ data }) => ({
312+
posts: data ?? emptyArray,
313+
}),
314+
})
315+
316+
return (
317+
<ul>
318+
{posts.map((post) => (
319+
<PostById key={post.id} id={post.id} />
320+
))}
321+
</ul>
322+
)
323+
}
324+
```
325+
326+
To summarize the above behaviour - the returned values must be correctly memoized. See also [Deriving Data with Selectors](https://redux.js.org/usage/deriving-data-selectors) and [Redux Essentials - RTK Query Advanced Patterns](https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#selecting-values-from-results) for additional information.
327+
300328
### Avoiding unnecessary requests
301329

302330
By default, if you add a component that makes the same query as an existing one, no request will be performed.

0 commit comments

Comments
 (0)