Fetching API in React.js

React.js Basics

In this post, I am going to explain step by step process to fetch API data in react.js. Before we start, we need to understand the first two basic concepts in React.js, i.e. useState and useEffect hooks in functional components.

  • useState: It is a special function that takes the initial state as an argument and returns an array of two entries. ("initialstate" can be anything like Boolean, integer, string, array, etc).

    syntax : const [data , setData] = useState(initialstate)

  • useEffect: Tasks like updating the DOM, fetching data from API, etc are some of its major use, and it reduces the unwarranted error that used to occur in class-based components.

    syntax : useEffect(() => { /* logic comes here */ });

import { useState , useEffect } from 'react'; 

export default function App(){
const [data , setData] = useState([]);

useEffect(() => {
    async function fetchData() {
      const response = await fetch("API end-point will come here");
      const responseJSON = await response.json();
      setData(responseJSON);
    }
    fetchData();
  }, []);
}

The async and await keywords enable implementation of asynchronous & promise-based behavior without writing promise chains explicitly.

NOTE: You can use different libraries available to fetch API like Axios, React Query library, etc.