How do you handle network requests in React Native?
Answer
React Native provides the Fetch API (same as browser) and you can use any JavaScript HTTP library. Fetch API (built-in): async function fetchUsers() { try { const response = await fetch("https://api.example.com/users", { method: "GET", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error("Fetch error:", error); throw error; } } // POST: const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Alice", email: "alice@example.com" }), });. Axios (popular library): import axios from "axios"; const api = axios.create({ baseURL: "https://api.example.com", timeout: 10000, headers: { "Content-Type": "application/json" }, }); // Interceptors for auth headers: api.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${getToken()}`; return config; }); const { data } = await api.get("/users"); const { data: user } = await api.post("/users", { name: "Alice" });. React Query (TanStack Query) for server state: import { useQuery, useMutation } from "@tanstack/react-query"; const { data, isLoading, error, refetch } = useQuery({ queryKey: ["users"], queryFn: fetchUsers, staleTime: 5 * 60 * 1000, }); const mutation = useMutation({ mutationFn: createUser, onSuccess: () => queryClient.invalidateQueries({ queryKey: ["users"] }) });. React Query handles caching, background refresh, retry, and loading/error states automatically — highly recommended for production apps.
More React Native Questions
View all →- Intermediate What is the React Native New Architecture?
- Intermediate What is React Navigation nested navigators?
- Intermediate What are Native Modules in React Native?
- Intermediate What is the difference between react-native-reanimated and the Animated API?
- Intermediate What is the React Native bridge and how does it work?