How to Fetch Data in React 18 Using the Fetch API

Last Updated on by in React JS

Fetch API allows developers to take an elegant approach to initiate network requests and render the data with correct response codes.

In this tutorial, you will learn through a series of steps: how to use the Fetch API in React to retrieve data from a server by sending a request to a web server, as well as how to show the data on the browser using the functional component, useState, useEffect hooks, and map method.

To mimic the server request, and data handling we will use https://jsonplaceholder.typicode.com/posts API.

Fetch API is a replacement for XMLHttpRequest (XHR), revolutionizes network requests by leveraging Promises, resulting in a cleaner and dynamic data handling.

This guide aims to provide a detailed understanding and implementation methodology, ensuring a robust grasp on getting data from the server using this fundamental Fetch API.

Step 1: Initializing Your React Project

Installing a React project, lays the foundation for using the Fetch API in React.

You can use ‘create-react-app’ command to scaffold a new React application, offers an organized environment to implement data fetching mechanisms.

npx create-react-app cruise-app

Next, move into the app folder.

cd cruise-app

If you already have the app, jump on to the subsequent step.

Step 2: Constructing the Component Structure

Through the creation of components, like ‘Posts.js’, developers lays a foundation to structure and encapsulate their custom functions and methods.

Code goes to: components/Posts.js

import React from 'react'

export default function Posts() {
    return (
        <div>
            
        </div>
    )
}

Step 3: Fetching Data via the Fetch API

In below code example, we are employing `useState` and `useEffect` hooks that are concurrently performing multiple tasks, from managing component states and side effects to rendering the records in simple component.

Code goes to: components/Posts.js

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

export default function Posts() {
  const [post, getPost] = useState([])

  const API = 'https://jsonplaceholder.typicode.com/posts';

  const fetchPost = () => {
    fetch(API)
      .then((res) => res.json())
      .then((res) => {
        console.log(res)
        getPost(res)
      })
  }

  useEffect(() => {
    fetchPost()
  }, [])

  return (
    <>
      <h2>React Fetch Data with REST API Example</h2>
      <ul>
        {post.map((item, i) => {
          return <li key={i}>{item.title}</li>
        })}
      </ul>
    </>
  )
}

Step 4: Integration of New Component

Integrate the developed components into the primary application file (‘App.js’).

import React from 'react'
import Posts from './components/Posts'

function App() {
  return (
    <div className="container">
      <Posts />
    </div>
  )
}

export default App

Step 5: App Testing

Execute below command to start the application to validate the effectiveness of the React data fetching mechanism.

npm start

How to Use Fetch API to Get Data in React with REST API

FAQs – Frequently Asked Questions

What distinguishes the Fetch API from XMLHttpRequest (XHR)?

The Fetch API streamlines network requests through its Promise-based design, giving a more intuitive and cleaner ways compared to traditional XHR, resulting in enhancing the developer experience.

How do React hooks complement data fetching in functional components?

React hooks, `useState` and `useEffect`, plays crucial role for managing data states, they help in executing side effects inside the functional components, provides seamless data retrieval and managing processes.

What role does the Fetch method play in rendering data from the server in React?

The Fetch method provides server request handling environment, seamlessly handles the server responses, facilitates the dynamic content rendering in JavaScript powered web applications.