I am using react-query hook for data fetching. I have some filters (Playground). I want to call the api only when the applied filters are valid. I am using enabled
property to conditionally fetch. But my concern is, I have passed a function to enabled property which would be executed on every re-render. So, if I click on Re-render
button, even though my filters was not changed, but the isFiltersValid
function is called. In this example isFiltersValid is not a heavy computation, but what if it was a heavy computation function.
In case, if I just use useEffect, my code would look like:
useEffect(()=>{
// here `isFiltersValid` is called only when filters change and not on every re-render
if(isFiltersValid(filters)){
queryFn()
}
},[filters])
How can I stop executing the isFiltersValid
when filters are not changed. I can either memoize the result of isFiltersValid or can have a state which tells whether the status is valid or not and then I can pass that value to enabled
. But is there any other approach without useMemo
or using a state
?