Reputation: 6265
I have set up RTK Query as an API layer within my application. This replaced data previously stored in redux which was being used to build selectors (using CreateSelector from reselect).
Now with RTK Query, everything is in hooks, so naturally I attempted to move the logic in CreateSelector to various hooks being sourced with RTK Query results like so:
useSelectStoreDetailedData = () => {
const {storesData} = useListStoresQuery()
const {productsData} = useListProductsQuery()
const {pricesData} = useListPricesQuery()
return useMemo(()=> runExpensiveFunc(storesData, productsData, pricesData),
[storesData, productsData, pricesData])
}
This works fine when 1 component is calling this hook, but if many components need this data, each component making a call to the hook (i.e. useSelectStoreDetailedData()
) causes the data to be reprocessed from scratch since it's mounting another instance of the hook. Since it's a very expensive operation, this is causing the application to visibly slow down.
I've tried taking this expensive function and memoizing it using lodash memoize
function but it's also a costly operation to determine equality.
Is there some better pattern for sharing this api-sourced computation across components?
Upvotes: 0
Views: 1158
Reputation: 44186
You could just use your reselect
selector.
const selector = createSelector(...)
useSelectStoreDetailedData = () => {
const {storesData} = useListStoresQuery()
const {productsData} = useListProductsQuery()
const {pricesData} = useListPricesQuery()
return selector(storesData, productsData, pricesData)
}
Upvotes: 1