Categories
React Answers

How to do API call in React?

Spread the love

Sometimes, we want to do API call in React.

In this article, we’ll look at how to do API call in React.

How to do API call in React?

To do API call in React, we call the useEffect hook.

For instance, we write

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

const Comp = () => {
  //...
  useEffect(() => {
    fetchDataFromBackend();
  }, []);
  //...
};

to call useEffect in the Comp component with a callback that calls fetchDataFromBackend to make the request to the API we want.

We call useEffect with an empty array so that the callback only runs when the component mounts.

Conclusion

To do API call in React, we call the useEffect hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *