...

/

Pulling in Data for the App

Pulling in Data for the App

Learn how to efficiently fetch and manage data throughout your app, utilizing React Context to avoid prop drilling and ensuring smooth data flow in a complex application structure.

Let’s fetch some data and use some state!

Fetching the users data

We’ll start with fetching the list of users. This list contains user IDs and links to user avatars. Our API depends on us to manage the user avatars everywhere in the app and passes them in this one endpoint only.

Press + to interact

So, let’s check where we need the list of users:

  • We need it on the “Feed” surface to display the list of avatars.

  • We will also need it to display avatars on the cards on the “Feed” surface.

  • We will also need the user data on the “Conversations” surface and the “Messages” surface.

At this point, it will be beneficial to find the common parent of those surfaces and call our API in the said parent. In our case, the parent is the root component declared in App.js.

The first thing we’ll do is fetch our data in the parent:

Press + to interact
// src/App.js
export default function App() {
const [userLoggedIn, setIsUserLoggedIn] = useState(true);
const [userList, setUserList] = useState(null);
//...
async function fetchUserData(id) {
const response = await fetch(requestBase + "/users.json");
setUserList(await response.json());
}
useEffect(() => {
fetchUserData();
}, []);
//...
if (!userList) {
return <AppLoading />;
}

Passing data from parent to children

Once we have our data fetched and inside the userList object, we can pass it as a prop from the parent component to the children. According to the React Navigation docs, we can pass additional props through the render callback of the navigator. Here’s what it would look like for the Home component:

Press + to interact
<Stack.Screen name='Home' options={{ headerShown: false }}>
{(props) => <Home {...props} userList={userList} />}
</Stack.Screen>

Once we have the userList prop in the Home surface, we should be done, yes? Unfortunately, no. The Home surface is a parent for the tab navigator, so we need to do the whole song and dance of adding the render callback for the Feed surface. Once we get to the Feed surface, we will need to pass the userList prop to the ListOfAvatars component. This is starting to be a bit much. This is a taste of what would be called prop drilling in a bigger app. Passing an object through multiple surfaces and components is not only tedious but also error-prone. This sort of setup is brittle—it suffices that one component in the chain changes, and the whole app might become unusable. What can we do to avoid this? We can use React Context. This is also the strategy recommended by the ...