Bird
Raised Fist0
React Nativemobile~20 mins

React Query for data fetching in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User List Screen
This screen fetches and displays a list of users from a remote API using React Query. It shows loading and error states and allows refreshing the list.
Target UI
-------------------------
|      User List         |
|-----------------------|
| [Loading spinner...]   |
|                       |
|                       |
|                       |
|                       |
|                       |
|-----------------------|
| Refresh Button         |
-------------------------
Use React Query to fetch user data from https://jsonplaceholder.typicode.com/users
Show a loading indicator while fetching data
Display an error message if fetching fails
Render the list of user names in a scrollable list
Add a Refresh button to refetch the data on demand
Starter Code
React Native
import React from 'react';
import { View, Text, Button, FlatList, ActivityIndicator, StyleSheet } from 'react-native';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';

const queryClient = new QueryClient();

function UserList() {
  // TODO: Use useQuery to fetch users

  return (
    <View style={styles.container}>
      {/* TODO: Show loading indicator */}
      {/* TODO: Show error message */}
      {/* TODO: Render FlatList of users */}
      {/* TODO: Add Refresh button */}
    </View>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <UserList />
    </QueryClientProvider>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#fff' },
  item: { padding: 12, borderBottomWidth: 1, borderBottomColor: '#ccc' },
  errorText: { color: 'red', marginBottom: 10 },
  loading: { marginVertical: 20 }
});
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
React Native
import React from 'react';
import { View, Text, Button, FlatList, ActivityIndicator, StyleSheet } from 'react-native';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';

const queryClient = new QueryClient();

function UserList() {
  const { data, error, isLoading, refetch } = useQuery(['users'], async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json();
  });

  if (isLoading) {
    return <ActivityIndicator size="large" style={styles.loading} accessibilityLabel="Loading users" />;
  }

  if (error) {
    return (
      <View style={styles.container}>
        <Text style={styles.errorText} accessibilityRole="alert">Error loading users: {error.message}</Text>
        <Button title="Retry" onPress={refetch} accessibilityLabel="Retry fetching users" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => <Text style={styles.item}>{item.name}</Text>}
        accessibilityLabel="User list"
      />
      <Button title="Refresh" onPress={refetch} accessibilityLabel="Refresh user list" />
    </View>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <UserList />
    </QueryClientProvider>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#fff' },
  item: { padding: 12, borderBottomWidth: 1, borderBottomColor: '#ccc', fontSize: 16 },
  errorText: { color: 'red', marginBottom: 10, fontSize: 16 },
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});

We use the useQuery hook from React Query to fetch the user data asynchronously. It manages loading, error, and data states for us.

While loading, we show an ActivityIndicator spinner. If an error happens, we display a red error message and a Retry button that calls refetch.

When data is loaded, we render a FlatList showing user names. The Refresh button also calls refetch to reload the data on demand.

This approach keeps the UI responsive and handles network states cleanly with minimal code.

Final Result
Completed Screen
-------------------------
|      User List         |
|-----------------------|
| Leanne Graham          |
| Ervin Howell           |
| Clementine Bauch       |
| Patricia Lebsack       |
| Chelsey Dietrich       |
| Mrs. Dennis Schulist   |
| Kurtis Weissnat        |
| Nicholas Runolfsdottir |
| Glenna Reichert        |
| Clementina DuBuque     |
|-----------------------|
| Refresh Button         |
-------------------------
When the screen loads, a spinner shows until users are fetched.
If fetching fails, an error message and Retry button appear.
User names appear in a scrollable list after loading.
Pressing Refresh button reloads the user list from the API.
Stretch Goal
Add pull-to-refresh functionality to reload the user list by pulling down on the list.
💡 Hint
Use FlatList's refreshing and onRefresh props with React Query's isFetching and refetch.

Practice

(1/5)
1. What is the main purpose of using useQuery in React Query for React Native apps?
easy
A. To style components dynamically
B. To fetch and manage server data easily with caching and updates
C. To navigate between screens
D. To handle local state only

Solution

  1. Step 1: Understand the role of useQuery

    useQuery is designed to fetch data from a server and manage it efficiently in React apps.
  2. Step 2: Identify its features

    It automatically handles loading states, errors, caching, and data updates, making server data management easier.
  3. Final Answer:

    To fetch and manage server data easily with caching and updates -> Option B
  4. Quick Check:

    useQuery purpose = fetch and manage data [OK]
Hint: Remember: useQuery is for fetching and caching data [OK]
Common Mistakes:
  • Confusing useQuery with navigation or styling hooks
  • Thinking useQuery manages only local state
  • Assuming useQuery is for UI rendering only
2. Which of the following is the correct syntax to use useQuery to fetch data with a key 'todos' and a fetch function fetchTodos?
easy
A. const { data } = useQuery('todos', fetchTodos);
B. const data = useQuery(fetchTodos, 'todos');
C. useQuery(fetchTodos, { key: 'todos' });
D. const { data } = useQuery({ key: 'todos', fetch: fetchTodos });

Solution

  1. Step 1: Recall the useQuery syntax

    The correct syntax is useQuery(key, fetchFunction), where the first argument is a unique key and the second is the function to fetch data.
  2. Step 2: Match the options

    const { data } = useQuery('todos', fetchTodos); matches this syntax exactly: useQuery('todos', fetchTodos).
  3. Final Answer:

    const { data } = useQuery('todos', fetchTodos); -> Option A
  4. Quick Check:

    useQuery(key, fetchFn) = const { data } = useQuery('todos', fetchTodos); [OK]
Hint: useQuery takes key first, then fetch function [OK]
Common Mistakes:
  • Swapping the order of arguments
  • Passing an object instead of separate arguments
  • Not destructuring the returned data
3. Given this code snippet:
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?
medium
A. Loading...
B. Error!
C. Alice is 30 years old.
D. undefined is undefined years old.

Solution

  1. 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'.
  2. 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.
  3. Final Answer:

    Alice is 30 years old. -> Option C
  4. Quick Check:

    Data loaded = Alice is 30 years old [OK]
Hint: Check loading and error before rendering data [OK]
Common Mistakes:
  • Ignoring loading or error states
  • Accessing data before it loads
  • Assuming data is undefined
4. Identify the error in this React Query usage:
const { data, isLoading } = useQuery(fetchPosts, 'posts');
medium
A. The arguments to useQuery are reversed; key should come first
B. useQuery requires a third argument for options
C. Destructuring data and isLoading is not allowed
D. fetchPosts should be a string, not a function

Solution

  1. Step 1: Check the argument order for useQuery

    The correct order is useQuery(key, fetchFunction). Here, the fetch function is passed first, then the key.
  2. Step 2: Identify the mistake

    The arguments are reversed, which will cause an error or unexpected behavior.
  3. Final Answer:

    The arguments to useQuery are reversed; key should come first -> Option A
  4. Quick Check:

    useQuery(key, fetchFn) order matters [OK]
Hint: Key always comes before fetch function in useQuery [OK]
Common Mistakes:
  • Swapping key and fetch function arguments
  • Forgetting to pass a unique key
  • Assuming fetch function can be a string
5. You want to fetch a list of posts and automatically refetch the data every 10 seconds using React Query. Which code snippet correctly implements this behavior?
hard
A. const { data } = useQuery('posts', fetchPosts, { staleTime: 10000 });
B. const { data } = useQuery('posts', fetchPosts, { refetchOnWindowFocus: true });
C. const { data } = useQuery('posts', fetchPosts, { cacheTime: 10000 });
D. const { data } = useQuery('posts', fetchPosts, { refetchInterval: 10000 });

Solution

  1. Step 1: Understand refetching options in React Query

    To refetch data automatically at intervals, use the refetchInterval option with the interval time in milliseconds.
  2. Step 2: Match the correct option

    const { data } = useQuery('posts', fetchPosts, { refetchInterval: 10000 }); uses refetchInterval: 10000 which means refetch every 10 seconds. Other options control different behaviors.
  3. Final Answer:

    const { data } = useQuery('posts', fetchPosts, { refetchInterval: 10000 }); -> Option D
  4. Quick Check:

    Auto refetch = refetchInterval option [OK]
Hint: Use refetchInterval to auto-refresh data periodically [OK]
Common Mistakes:
  • Confusing refetchOnWindowFocus with interval refetch
  • Using cacheTime or staleTime incorrectly
  • Not passing options as third argument
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard