Light Refactoring
Before we start, let's do some light refactoring by optimising our imports. In Part 1, when we needed components and screens, we imported them on separate lines. As our app grows, there could be many import statements making the code harder to read.
We can reduce the number of import statements, by creating an index.ts file in each folder that lists the components/screens in each folder. It will list each component/screen as named exports, which can be imported on one line. This is the same syntax we use to import components, such as View and Text from 'react-native'. For example, import { View, Text } from 'react-native'.
Add Index File to Components Folder
First we will create an index.ts for the components folder.
- In the
componentsfolder and create a new file calledindex.ts. We use the.tsextension, because this is a pure TypeScript file that doesn't contain any JSX.
src/
├── components/
│ ├── Header.tsx
│ ├── VideoCard.tsx
| └── index.ts
└── App.tsx
- Open
index.tsand add import statements for every component in thecomponentsfolder. - Add an export statement that lists each component.
The index.ts file should look like this:
import Header from './Header';
import VideoCard from './VideoCard';
export {
Header,
VideoCard
}
Import Components
Next, we need to update LandingScreen.tsx to use the new imports approach.
- In the
LandingScreen.tsxremove the import statements for Header and VideoCard. - Add one import statement that adds the components from
index.ts. Note that we only need to specify the import from thecomponentsfolder, as theindex.tsfile will be read in this folder to find the named exports (Header, VideoCard).
The import statements in LandingScreen.tsx should look like this:
import React, {useState, useEffect} from 'react';
import {FlatList, StyleSheet, View} from 'react-native';
import {Header, VideoCard} from '../components';
Add Index File to Screens Folder
Now we will repeat the process for the screens folder.
- Create a file called
index.tsin thescreensfolder.
src/
├── screens/
│ ├── LandingScreen.tsx
| └── index.ts
└── App.tsx
- Open
index.tsand add import statements for every component in thescreensfolder. - Add an export statement that lists each component.
The index.ts file should look like this:
import LandingScreen from './LandingScreen';
export {
LandingScreen,
}
Import Screens
Now we need to update the import statements in App.tsx.
- Open
App.tsx. - Remove the import statement for LandingScreen.
- Add one import statement that adds the LandingScreen screen from the
screensfolder.
The import statements in App.tsx should now look like this:
import * as React from 'react';
import {LandingScreen} from './screens';
- Reload the app and verify that everything renders the same.
This refactoring may not seem like much, but as you build complex applications with many components and screens, this will help you reduce the number of import statements at the top of each file.

