Side Effects & Data Fetching

7 min read

Side Effects & Data Fetching 📡

Welcome, intrepid coder, to the exciting world of side effects and data fetching in React Native! So far, you've been building beautiful, self-contained components. But what happens when your app needs to talk to the outside world? 🤔 That's where things get interesting.

This guide will walk you through the essentials of managing external data, from fetching it from a server to displaying it in your app, all while keeping your user experience smooth and delightful.


1. The useEffect Hook: Timing is Everything ⏱️

The Problem: Your React Native components are great at rendering UI based on their current props and state. But what if you need to do something that isn't directly related to rendering? For instance:

  • Fetching data from a server when a component loads.
  • Setting up a subscription to a real-time service.
  • Manually changing the device's status bar color.

These are all "side effects" because they affect things outside of your component's direct control. Doing them directly in the main body of your component can lead to unpredictable behavior and performance issues.

The Solution: useEffect

The useEffect hook is your go-to tool for handling side effects in functional components. It allows you to run code after your component has rendered. Think of it as a way to say, "Hey React, after you're done drawing everything, please run this piece of code for me."

Here’s the basic syntax:

javascript
import React, { useEffect } from 'react';

useEffect(() => {
  // Your side effect code goes here
});

Controlling When Effects Run: The Dependency Array

By default, useEffect runs after every render. This can be inefficient. To control this, you provide a "dependency array" as a second argument.

  • Run Once on Mount: To run an effect only once when the component first mounts (like componentDidMount in class components), pass an empty dependency array ([]). This is perfect for initial data fetching.

    javascript
    useEffect(() => {
      console.log('This will only run once!');
    }, []);
  • Run When a Value Changes: To re-run the effect only when a specific value (a prop or state) changes, include that value in the dependency array.

    javascript
    useEffect(() => {
      console.log(`The user's name is now: ${userName}`);
    }, [userName]);

An Interesting Fact: The useEffect hook effectively combines the functionality of three classic lifecycle methods from class components: componentDidMount, componentDidUpdate, and componentWillUnmount. This makes your functional components cleaner and more organized.


2. Fetching Data from REST APIs 🌐

The Problem: Your app needs to display information that lives on a server. This could be a list of products, a user's profile, or the latest news articles. How do you get that data into your app?

The Solution: The fetch API

React Native provides the fetch API for making network requests. It's a powerful and flexible way to communicate with servers. For fetching data from a REST API, you'll typically make a GET request.

Here's a simple example of fetching a list of movies:

javascript
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';

const MovieList = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    fetch('https://reactnative.dev/movies.json')
      .then((response) => response.json())
      .then((json) => setMovies(json.movies))
      .catch((error) => console.error(error));
  }, []);

  return (
    <View>
      {movies.map((movie) => (
        <Text key={movie.id}>{movie.title}</Text>
      ))}
    </View>
  );
};

Under the Hood: The fetch function returns a "Promise." A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. The .then() blocks allow you to handle the successful response, and .catch() lets you deal with any errors that occur.

Industry Standard: Axios

While fetch is built-in, many developers prefer a library called Axios. Axios offers a simpler syntax, better error handling, and other convenient features.

To use Axios, you first need to install it:

bash
npm install axios

Then, you can use it in your component:

javascript
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

const MovieList = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    axios.get('https://reactnative.dev/movies.json')
      .then(response => {
        setMovies(response.data.movies);
      })
      .catch(error => {
        console.error(error);
      });
  }, []);

  // ... rendering logic
};

3. Handling Loading & Error States Gracefully ⏳❌

The Problem: Network requests take time. What does the user see while the data is loading? And what happens if the request fails due to a network issue or a server problem? A blank screen or a crashed app is a terrible user experience.

The Solution: State Management for Loading and Errors

The key is to use state variables to track the status of your data fetching operation. You'll typically need three states:

  1. loading: To know when to show a loading indicator.
  2. data: To store the successfully fetched data.
  3. error: To hold any error information if the request fails.

Let's enhance our movie list example to include loading and error handling:

javascript
import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator, Button } from 'react-native';
import axios from 'axios';

const MovieList = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  const fetchData = () => {
    setLoading(true);
    setError(null);
    axios.get('https://reactnative.dev/movies.json')
      .then(response => {
        setData(response.data.movies);
        setLoading(false);
      })
      .catch(error => {
        setError(error);
        setLoading(false);
      });
  };

  useEffect(() => {
    fetchData();
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  if (error) {
    return (
      <View>
        <Text>Error fetching data: {error.message}</Text>
        <Button title="Try Again" onPress={fetchData} />
      </View>
    );
  }

  return (
    <View>
      {data.map((movie) => (
        <Text key={movie.id}>{movie.title}</Text>
      ))}
    </View>
  );
};

A Funny Exaggeration: Imagine your app is a chef in a restaurant. If a customer orders a dish (data), you wouldn't just stand there silently while you cook. You'd say, "Coming right up!" (the loading state). And if you accidentally burn the toast (an error), you'd apologize and offer to make it again, not just throw the burnt toast at them and run away.


4. Integrating Remote Data into Lists 📜

The Problem: You've successfully fetched a list of items from an API. Now you need to display them in a scrollable list. A simple map as shown above works, but it can be inefficient for long lists.

The Solution: FlatList

React Native's FlatList component is designed for rendering long, scrollable lists of data efficiently. It only renders the items that are currently visible on the screen, which saves memory and improves performance.

To use FlatList, you need to provide two key props:

  • data: The array of data to be rendered.
  • renderItem: A function that takes an item from the data array and returns a React component to render for that item.

Let's refactor our movie list to use FlatList:

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

const MovieList = () => {
  // ... (loading, data, error state and fetchData logic from the previous example)

  const renderItem = ({ item }) => (
    <View style={styles.item}>
      <Text style={styles.title}>{item.title}</Text>
      <Text>{item.releaseYear}</Text>
    </View>
  );

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  // ... (error handling UI)

  return (
    <SafeAreaView>
      <FlatList
        data={data}
        renderItem={renderItem}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 24,
  },
});

The keyExtractor Prop: This prop tells the FlatList how to get a unique key for each item. This is crucial for React to efficiently update the list when data changes.

Real-world Scenario: Think of your social media feed. It would be incredibly slow and memory-intensive if the app tried to render every single post at once. Instead, it uses a virtualized list (like FlatList) to only render the posts you can currently see, loading more as you scroll.


📚 Further Reading & References

Challenge

You are tasked with building a React Native component that fetches a list of users from a public API and displays them efficiently.

Requirements:

  1. Create a functional component named UserList.
  2. Use the useState hook to manage three pieces of state: loading (initially true), users (initially an empty array), and error (initially null).
  3. Use the useEffect hook to fetch data from the following URL when the component first mounts: https://jsonplaceholder.typicode.com/users.
  4. Inside the useEffect hook, use the fetch API to make the GET request.
    • On a successful response, parse the JSON, update the users state with the fetched data, and set loading to false.
    • If an error occurs during the fetch, update the error state with a relevant error message string, and set loading to false.
  5. Implement conditional rendering in your component's return statement:
    • If loading is true, render a single <ActivityIndicator size="large" />.
    • If error is not null, render a <Text> component displaying the error message.
    • If the data has been successfully fetched, render a <FlatList />.
  6. Configure the <FlatList /> with the following props:
    • data: Should be bound to your users state.
    • keyExtractor: A function that returns the unique id for each user item (e.g., item.id.toString()).
    • renderItem: A function that destructures { item } from its argument and returns a <View> component for each user. Inside this <View>, display the user's name and email in separate <Text> components.

Expected result

Your final code should be a single React Native functional component called UserList.

The component must contain:

  • Three state variables declared using useState: loading, users, and error, with appropriate initial values.
  • A useEffect hook with an empty dependency array ([]) to ensure it runs only once on mount.
  • Inside the useEffect, a fetch call to 'https://jsonplaceholder.typicode.com/users'.
  • Promise handling (.then() and .catch()) for the fetch request. The success path should parse the JSON response and update the users and loading states. The failure path should update the error and loading states.
  • A return statement that implements conditional rendering:
    • It first checks the loading state and returns an <ActivityIndicator /> if true.
    • It then checks the error state and returns a <Text> component with the error message if an error exists.
    • Otherwise, it returns a <FlatList />.
  • The <FlatList /> component must have its data, renderItem, and keyExtractor props correctly configured.
    • The renderItem function should return a JSX structure that includes a <View> wrapping two <Text> elements for the user's name and email.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.