React Native is an extensive iOS/Android development framework that has many features. One of the areas that I personally struggled with in React Native during my most recent project was when I needed to have all of my fonts and images loaded prior to the user using the app. Fortunately, React Native has a feature that will let you dictate what needs to be loaded prior to the App running. Let’s run through an example of pre-loading in images and fonts in an App.
To start, you will need to have your fonts saved locally, and in this example, I’ll also have my images saved locally as well. I usually create an Assets folder that will hold my fonts and images, as seen in the image on the left.
Next, we will need to navigate to our App.js file, and we will create two functions, one to cover the font fetching and one to cover the image fetching. Before we create these two functions, we will need to import in two elements, one from ‘expo-asset’ and the entire ‘expo-font’ folder. Place these two lines at the top of your App.js file:
Next we will create our fetchFonts function:
You will notice we are loading the font .otf folders seen in the assets folder in a Font.loadAsync function.
Next we will need to craft our fetchImages function:
We now have our two fetching functions created for both fonts and images. Next, we will actually implement the AppLoading conditional logic in App.js.
First, we will need to import AppLoading like this:
AppLoading is a tool from Expo, which allows us to keep track of the loading and let’s perform an action when the loading is complete. Now with this, we will want to create a isLoading useState variable, which will be used in determining when to show our App. Additionally, we will want to create an async function that calls the two fetch functions.
Here is our ending result:
In this walkthrough, you learned how to fetch assets (images and fonts in this case) prior to the user being able to use the App, which eliminates half loaded pages.