Search code examples
reactjsreact-functional-componentrtk-query

RTK Query - Default Cache Behavior not clearing


I have a functional component(modal) that uses a custom hook that uses a lazy query. I confirmed the component unmounts via a useEffect:

  useEffect(() => {
    return () => {
      console.log('modal unmount')
    }
  }, [])

However after 60 seconds, the query result remains in Redux despite what the documentation states: https://redux-toolkit.js.org/rtk-query/usage/cache-behavior

As long as there is an active 'subscription' to the data (e.g. if a component is mounted that calls a useQuery hook for the endpoint), then the data will remain in the cache. Once the subscription is removed (e.g. when last component subscribed to the data unmounts), after an amount of time (default 60 seconds), the data will be removed from the cache.

So the implementation is route-->landing component-->modal-->custom hook-->RTK query and the cache entry never goes away after I close the modal, see the unmount and wait 60 seconds.


Solution

  • The most likely reason for that would be that you did not include api.middleware in the store setup.

    You should have warnings about that in your console.

    Another reason could be that you still have other components subscribed to that slice - you can see the subscribers in the RTK Query devtools.