Possible to derive multiple values from selectFromResult
without causing re-renders?
#4716
-
I have a custom hook for my query that accepts a selector function similarly as shown in the docs. Here is a rough idea of what the hook looks like: // Rough idea how the hook works:
export const useMyCustomHook = <T>(selector?: (result: Result) => T) => {
const { data, isError, isLoading } = useGetSomething(undefined, {
selectFromResult: (result) => ({
...result,
data: selector ? selector(result) : result.data,
}),
});
if (selector) {
return {
data: data as T,
isLoading,
isError,
};
}
return {
data,
isLoading,
isError,
};
};
// using the hook
const { data, isLoading, isError } = useMyCustomHook((result) =>
selectFoo(result),
); However, I would possibly like to derive other information as well. Would it be possible to derive additional information in a way similar to how const {
data: { foo, bar },
isLoading,
isError,
} = useMyCustomHook((result) => ({
foo: selectFoo(result),
bar: selectBar(result),
})); The latter code "works", but it creates a new object on each render, so it will cause unnecessary re-renders. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You can return as many additional fields as you want for the |
Beta Was this translation helpful? Give feedback.
Along those lines, just make sure you create the selector instance outside the component so it sticks around and can memoize properly:
https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#selecting-values-from-results