React Query helps you get data from the internet easily and keeps it fresh. It saves you from writing lots of code to handle loading and errors.
React Query for data fetching in React Native
import { useQuery } from '@tanstack/react-query'; const { data, error, isLoading } = useQuery({ queryKey: ['key'], queryFn: async () => { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); } });
useQuery is a hook that fetches and manages data.
queryKey is a unique name for the data you want to fetch.
const { data, isLoading } = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('https://jsonplaceholder.typicode.com/todos').then(res => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
});const { data, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`https://api.example.com/user/${userId}`).then(res => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
});This app fetches a list of todos from the internet and shows them in a scrollable list. It shows a loading spinner while waiting and an error message if something goes wrong.
import React from 'react'; import { View, Text, ActivityIndicator, FlatList } from 'react-native'; import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; const queryClient = new QueryClient(); function Todos() { const { data, error, isLoading } = useQuery({ queryKey: ['todos'], queryFn: () => fetch('https://jsonplaceholder.typicode.com/todos').then(res => { if (!res.ok) { throw new Error('Network response was not ok'); } return res.json(); }) }); if (isLoading) return <ActivityIndicator size="large" />; if (error) return <Text>Error loading todos.</Text>; return ( <FlatList data={data} keyExtractor={item => item.id.toString()} renderItem={({ item }) => <Text>{item.title}</Text>} /> ); } export default function App() { return ( <QueryClientProvider client={queryClient}> <View style={{ flex: 1, padding: 20, marginTop: 50 }}> <Text style={{ fontSize: 24, marginBottom: 10 }}>Todo List</Text> <Todos /> </View> </QueryClientProvider> ); }
React Query automatically caches data to make your app faster.
It handles loading and error states so you don't have to write extra code.
Always wrap your app with QueryClientProvider to use React Query.
React Query makes fetching and managing server data easy in React Native apps.
Use useQuery with a unique key and a function that fetches data.
It helps with loading, errors, caching, and updating data automatically.
Practice
useQuery in React Query for React Native apps?Solution
Step 1: Understand the role of
useQueryuseQueryis designed to fetch data from a server and manage it efficiently in React apps.Step 2: Identify its features
It automatically handles loading states, errors, caching, and data updates, making server data management easier.Final Answer:
To fetch and manage server data easily with caching and updates -> Option BQuick Check:
useQuery purpose = fetch and manage data [OK]
- Confusing useQuery with navigation or styling hooks
- Thinking useQuery manages only local state
- Assuming useQuery is for UI rendering only
useQuery to fetch data with a key 'todos' and a fetch function fetchTodos?Solution
Step 1: Recall the useQuery syntax
The correct syntax isuseQuery(key, fetchFunction), where the first argument is a unique key and the second is the function to fetch data.Step 2: Match the options
const { data } = useQuery('todos', fetchTodos); matches this syntax exactly:useQuery('todos', fetchTodos).Final Answer:
const { data } = useQuery('todos', fetchTodos); -> Option AQuick Check:
useQuery(key, fetchFn) = const { data } = useQuery('todos', fetchTodos); [OK]
- Swapping the order of arguments
- Passing an object instead of separate arguments
- Not destructuring the returned data
const fetchUser = async () => {
return { name: 'Alice', age: 30 };
};
const { data, isLoading, error } = useQuery('user', fetchUser);
if (isLoading) return <Text>Loading...</Text>;
if (error) return <Text>Error!</Text>;
return <Text>{data.name} is {data.age} years old.</Text>;What will be displayed after the data loads successfully?
Solution
Step 1: Analyze the fetch function and query
The fetchUser function returns an object with name 'Alice' and age 30. useQuery fetches this data with key 'user'.Step 2: Understand the rendering logic
While loading, it shows 'Loading...'. On error, it shows 'Error!'. After successful fetch, it renders the text with data values.Final Answer:
Alice is 30 years old. -> Option CQuick Check:
Data loaded = Alice is 30 years old [OK]
- Ignoring loading or error states
- Accessing data before it loads
- Assuming data is undefined
const { data, isLoading } = useQuery(fetchPosts, 'posts');Solution
Step 1: Check the argument order for useQuery
The correct order isuseQuery(key, fetchFunction). Here, the fetch function is passed first, then the key.Step 2: Identify the mistake
The arguments are reversed, which will cause an error or unexpected behavior.Final Answer:
The arguments to useQuery are reversed; key should come first -> Option AQuick Check:
useQuery(key, fetchFn) order matters [OK]
- Swapping key and fetch function arguments
- Forgetting to pass a unique key
- Assuming fetch function can be a string
Solution
Step 1: Understand refetching options in React Query
To refetch data automatically at intervals, use therefetchIntervaloption with the interval time in milliseconds.Step 2: Match the correct option
const { data } = useQuery('posts', fetchPosts, { refetchInterval: 10000 }); usesrefetchInterval: 10000which means refetch every 10 seconds. Other options control different behaviors.Final Answer:
const { data } = useQuery('posts', fetchPosts, { refetchInterval: 10000 }); -> Option DQuick Check:
Auto refetch = refetchInterval option [OK]
- Confusing refetchOnWindowFocus with interval refetch
- Using cacheTime or staleTime incorrectly
- Not passing options as third argument
Ready to prove it?
Pass the test and this pattern moves unknown
