Simple Usage in React Native Application with useEffect, useState and FlatList.

Yigithan
3 min readNov 24, 2023

--

In this React Native code snippet, we leverage the power of useEffect, useState, and FlatList to create a well-structured and responsive mobile application. The primary goal is to fetch and display posts from a remote API while ensuring a smooth user experience.

import React, {useEffect, useState} from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
SafeAreaView,
ActivityIndicator,
} from 'react-native';

interface Post {
userId: number;
id: number;
title: string;
body: string;
}

function App(): JSX.Element {
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<boolean>(false);

useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
setError(false);
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts',
);
const result = await response.json();
setPosts(result);
setLoading(false);
setError(false);
} catch (error) {
console.error('Failed to fetch data', error);
setLoading(false);
setError(true);
}
};

fetchPosts();
}, []);

return (
<>
<SafeAreaView style={styles.container}>
<Text style={styles.headerText}>React Native App</Text>

{loading == true ? (
<View style={styles.contain}>
<ActivityIndicator color={'red'} size={'large'} />
</View>
) : !loading && !error && posts.length !== 0 ? (
<FlatList
data={posts}
renderItem={({item, index}) => (
<View style={styles.postContainer}>
<Text style={styles.postTitle}>{item.title}</Text>
<Text style={styles.postBody}>{item.body}</Text>
</View>
)}
keyExtractor={item => item.id.toString()}
/>
) : !loading && !error && posts.length === 0 ? (
<View style={styles.contain}>
<Text style={styles.notFoundText}>{'Not Found!'}</Text>
</View>
) : !loading && error == true && posts.length === 0 ? (
<View style={styles.contain}>
<Text style={styles.errorText}>{'Error!'}</Text>
</View>
) : (
<></>
)}
</SafeAreaView>
</>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
alignItems: 'center',
backgroundColor: 'white',
},
headerText: {
fontSize: 20,
fontWeight: 'bold',
color: 'black',
marginVertical: 10,
},
postContainer: {
marginVertical: 5,
borderWidth: 1,
borderColor: 'black',
padding: 10,
borderRadius: 8,
},
contain: {
alignItems: 'center',
},
postTitle: {
fontSize: 18,
fontWeight: 'bold',
color: 'black',
},
postBody: {
fontSize: 14,
color: 'black',
},
notFoundText: {
fontSize: 14,
color: 'black',
},
errorText: {
fontSize: 14,
color: 'red',
},
});

export default App;

The useEffect hook plays a pivotal role in managing side effects in functional components. In this context, it orchestrates the asynchronous data fetching process. By combining it with useState, the application gracefully handles the loading state, indicating whether data retrieval is in progress. The useState hook, in conjunction with state variables like loading and error, allows for effective control flow and error handling.

Within the useEffect block, an asynchronous function (fetchPosts) is defined to retrieve post data from a specified API endpoint. The application presents a clean loading indicator, and in case of a successful fetch, the obtained data is set in the component’s state. Conversely, any errors during the fetch trigger appropriate error handling, preventing potential disruptions in the user experience.

Conditional rendering is seamlessly implemented using FlatList, a performant and memory-efficient component for rendering lists. The posts array, managed by useState, is efficiently mapped within the FlatList, populating the user interface with post titles and bodies. The conditional rendering logic ensures that the user receives clear feedback, whether posts are being loaded, if none are found, or if an error occurs.

The application’s user interface is enhanced with clear and intuitive styling. A SafeAreaView provides a safe zone for content, and styles defined using StyleSheet.create ensure consistency and readability. Different visual cues, such as an activity indicator for loading, distinguishable error messages, and clean post containers, contribute to an aesthetically pleasing and user-friendly design.

In summary, this React Native application showcases a robust implementation of essential hooks and components, creating a seamless experience for users interacting with remote data. The strategic use of useEffect, useState, and FlatList demonstrates a foundational understanding of React Native development principles, laying the groundwork for scalable and maintainable mobile applications.

Let’s not forget that the differences in data retrieval with useEffect and the way of retrieving data will be different in the future. This is just a simple example. I hope it was informative.

--

--