Search code examples
react-hooksredux-toolkitrtk-query

When do I use `useDispatch` & `useSelector` hooks with `RTK Query`?


I've started using Redux Toolkit with RTK Query for developing a client-side application that relies on API requests for data. However, I've come across a dilemma. Following the Redux Toolkit documentation, it's recommended to use RTK Query in container components and then pass the fetched data to presentational components. Yet, with this approach, I find myself not utilizing slices or Redux state at all. What would be the best approach in this scenario, and when should I use the useSelector and useDispatch hooks?


Solution

  • As per the documentation we can use rtk query to fetch the data and pass the data to component and presentational layers where. but there are few scenario where you will need to cache the data in redux store and use it throughout the app, in that case slice, useSelector, useDispatch hook comes in the picture. for example while user sign in, you can use useDispatch hook to store the user data in redux store with user slice. further you can use user data directly using useSelector throughout the app

    export const useAppDispatch = () => useDispatch<AppDispatch>();
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
    

    i.e auth layer

    const dispatch = useAppDispatch();
      const { data: userData, isLoading } = useGetUserQuery();
    
    useEffect(()=>{
    dispatch(setUserInfo(userData ));
    },[])
    

    and you can use store data throughout the app with useAppSelector

    const userData = useAppSelector((state: RootState) => state.user);