Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to use fetch in ReactJS

Introduction

In our daily life, we often need to fetch (grab or retrieve) information. It could be as simple as grabbing a book from a shelf or as complex as retrieving data from a cloud-based database. Similarly, in the world of programming, fetch is a concept that is used to retrieve data from a source. In this blog post, we will explore how to use fetch in ReactJS, a popular JavaScript library for building user interfaces.

What Exactly is Fetch?

In JavaScript, fetch is a function used for making network requests. It's a part of the Web API provided by the browser. In simpler terms, fetch is like an online courier. You give it an address (URL), it goes there, grabs the data, and brings it back to you.

What is ReactJS?

ReactJS is a JavaScript library created by Facebook. It's used for building user interfaces, particularly for single-page applications. You can think of it as a set of LEGO blocks. Each block (component) is built separately and then they are all brought together to create a beautiful structure (application).

Fetching Data in React

In a typical React application, you may need to fetch data from a server or an API (Application Programming Interface). An API can be thought of as a waiter in a restaurant. You (the client) make a request (order food) and the API (waiter) fetches the data (brings your food) from the server (kitchen).

Here's a simple code example of how you can use fetch in a React component.

class FetchData extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: null };
  }

  componentDidMount() {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  render() {
    return (
      <div>
        {this.state.data ? this.state.data : 'Fetching data...'}
      </div>
    );
  }
}

In the above code, we're creating a new React component called FetchData. When this component is first rendered on the screen, it will show 'Fetching data...' because the data state is initially set to null.

The componentDidMount() is a special method in React that gets called automatically after the component has been rendered on the screen. Inside this method, we're calling the fetch() function with the URL of the API we want to fetch data from.

The fetch() function returns a promise. If you're not familiar with promises, they can be thought of as a receipt for a future value. It's like when you order a pizza, the restaurant gives you a receipt promising that you'll get your pizza in the future. In the same way, the fetch() function promises to give us a response in the future.

Once we get the response, we convert it into JSON format using response.json(). This again returns another promise. When this promise resolves, we finally get the data we wanted and we update our component's data state with it.

The render() method is then automatically called again because of the state change, and this time it will display the fetched data.

Working with Fetch and useEffect Hook

In the previous example, we used a class component and the componentDidMount() lifecycle method to fetch data. However, with the introduction of Hooks in React 16.8, we can now fetch data in a functional component using the useEffect hook.

The useEffect hook can be thought of as a combination of componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods. It runs after the first render and after every update.

Here's how you can use fetch with the useEffect hook:

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

function FetchData() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? data : 'Fetching data...'}
    </div>
  );
}

export default FetchData;

In this example, we're using the useState hook to create a data state variable and the setData function to update this state. The useEffect hook is used to fetch data from the API. The empty array [] passed as the second argument to useEffect ensures that the fetching code only runs once after the first render.

Conclusion

Fetching data is a common requirement in most web applications and knowing how to use fetch in React is an essential skill for a React developer. We've covered how to use fetch in both class and functional components, and how to use it with the useEffect hook.

Remember, fetch is like an online courier that retrieves information for you. It's a powerful tool, but it's also important to handle it with care. Always make sure to handle any potential errors and to load data efficiently to provide the best user experience.

I hope this post has helped you understand how to use fetch in React. Happy coding!