Milind Daraniya

How to Consume REST APIs in React

Published August 26th, 2023 14 min read

Hello, React developers! we'll explore how to consume RESTful APIs in React applications. REST APIs are a fundamental way to interact with server-side data and services, and learning how to consume them is essential for building modern web applications. 

Set Up a New React Application 
If you don't have a React application already, you can create one using Create React App (CRA). Open your terminal and run the following command to create a new React project:

npx create-react-app react-api-example

Install Axios 
We'll use Axios, a popular JavaScript library, to make HTTP requests to the REST API. In the root directory of your React project, install Axios by running the following command:

npm install axios

Create a Component to Consume the API 
Now, let's create a new component called UserList that will consume a REST API to fetch and display a list of users. Create a file named UserList.js in the src directory of your React project:

// src/UserList.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const UserList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch the data from the REST API when the component mounts
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => setUsers(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

Render the Component in App.js 
Now, let's render the UserList component in the App.js file to see the list of users. Open the App.js file in the src directory and update it as follows:

// src/App.js
import React from 'react';
import UserList from './UserList';

function App() {
  return (
    <div>
      <h1>React API Example</h1>
      <UserList />
    </div>
  );
}

export default App;

Test the Application 
Now, start your React development server by running the following command in your project's root directory:

npm start

Visit http://localhost:3000 in your browser, and you should see the list of users fetched from the REST API displayed on the page.

Congratulations! 🎉 You've successfully consumed REST APIs in a React application.