Blog>
Snippets

Utilizing Custom Hooks for Reusable Store Logic

Demonstrate how to create and use custom React hooks that encapsulate TanStack Store logic for easy reuse across components.
import { useQuery } from 'react-query';

// Custom hook for fetching user data
function useUserData(userId) {
  return useQuery(['user', userId], () => fetchUserById(userId));
}

// Fetch user data function placeholder
async function fetchUserById(userId) {
  const response = await fetch(`/api/user/${userId}`);
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
}
This code snippet shows the creation of a custom hook, useUserData, which encapsulates the logic for fetching user data using TanStack Query's useQuery hook. It demonstrates how to fetch data by user ID and how to handle async operations within a custom hook.
import { useMutation, useQueryClient } from 'react-query';

// Custom hook for updating user data
function useUpdateUser() {
  const queryClient = useQueryClient();
  return useMutation(updateUser, {
    onSuccess: () => {
      queryClient.invalidateQueries('user');
    },
  });
}

// Update user function placeholder
async function updateUser(userData) {
  const response = await fetch('/api/user', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(userData),
  });
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
}
Here, a custom hook useUpdateUser is created to encapsulate the useMutation hook from TanStack Query for updating user data. The hook leverages the onSuccess option to automatically invalidate the 'user' query upon a successful mutation, ensuring the UI is synced with the latest data.