Blog>
Snippets

Combining React Query and Redux

Provide an example of how React Query can be used for server state management while Redux manages the client-side state in a React application.
import { useQuery } from 'react-query';
import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';
Imports necessary hooks from React Query and Redux, as well as axios for data fetching.
const fetchUserData = async (userId) => {
  const { data } = await axios.get(`/api/user/${userId}`);
  return data;
};
Defines an asynchronous function for fetching user data from a server using a user ID.
function UserInfo({ userId }) {
  // Using React Query for fetching and managing server state
  const { data: user, isLoading, isError } = useQuery(['user', userId], () => fetchUserData(userId));

  // Accessing and manipulating client state with Redux
  const userTheme = useSelector(state => state.userTheme);
  const dispatch = useDispatch();

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching user data</div>;

  const handleChangeTheme = () => {
    dispatch({ type: 'CHANGE_THEME', payload: user.favoriteTheme });
  };

  return (
    <div>
      <h1>{user.name}'s Info</h1>
      <p>Email: {user.email}</p>
      <p>Current Theme: {userTheme}</p>
      <button onClick={handleChangeTheme}>Change Theme</button>
    </div>
  );
}
A React component that uses React Query to fetch and display user data, and Redux to manage and update a client-side state (here, a theme).