Patterns for implementing data fetching in React applications (web and mobile) using SWR.
Component → SWR Hook → Fetcher → API Endpoint → Response
Component Mount → SWR Request → Fetcher Call → API Response → Component Update
lib/
├── fetcher.ts # SWR fetcher utility
└── api.ts # API configuration
hooks/
└── useProducts.ts # Custom SWR hooks
components/
└── ProductList.tsx # Components using SWR
Location: ./lib/fetcher.ts
Rules:
// ./lib/fetcher.ts (Web)
export const fetcher = async (url: string) => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${url}`, {
credentials: "include",
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) throw new Error("Failed to fetch data");
return res.json();
};
// ./lib/fetcher.ts (React Native)
export const fetcher = (url: string) => {
const accessToken = useAuthStore.getState().accessToken;
return fetch(`${API_URL}${url}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then(res => res.json());
};
Location: Component files
Rules:
@/lib/fetcher/api/v{x}/resourcemutate for manual revalidationimport useSWR from 'swr';
import { fetcher } from '@/lib/fetcher';
// In component
const { data, error, isLoading, mutate } = useSWR<ResponseType>(
'/api/v1/endpoint',
fetcher
);
Location: ./hooks/useProducts.ts
Rules:
// ./hooks/useProducts.ts
import useSWR from 'swr';
import { fetcher } from '@/lib/fetcher';
export function useProducts() {
return useSWR('/api/v1/products', fetcher);
}