Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Where in a React component should you make an AJAX request ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In most modern web applications, the backend is separated from the frontend. Therefore, it needs to fetch data from a remote endpoint(server), by making AJAX requests.

These AJAX requests should be made after the component has been rendered to the browser, and usually, they need to be made only once. Thus, the best place to make the requests is inside an useEffect hook. Let us take a look at how we can implement this.

Creating React Application: 

Step 1: Create a React application using the following command:

npx create-react-app myapp

Step 2: After creating your project folder, i.e. myapp, move to it using the following command:

cd myapp

Project Structure: It will look like the following.

Initial folder structure

Implementation: Now that we have the project set up, let us replace the content of App.js, located inside the src folder, with the following code.


import React, { useState, useEffect } from "react";
const App = () => {
  const [text, setText] = useState("Data has not been fetched yet!");
  useEffect(() => {
      .then((response) => response.json())
      .then(({ fact }) => setText(fact))
      .catch((error) => {
        setText("An error occurred!");
  }, []);
  return <div>{text}</div>;
export default App;

Step to run the application: Use the following command to run the app in development mode, and open http://localhost:3000 to view it in the browser:

npm start


Every time we reload, the displayed text changes from “Data has not been fetched yet!” to the response data

Explanation: Here, we make an AJAX request inside the useEffect hook, taking the help of a free-to-use API. The useEffect hook has a second parameter: an empty array. This array is known as the dependency array, and if any item present in the dependency array changes between successive renders of the component, the code inside that useEffect is executed (there can be more than one useEffect in a component). Thus, an empty dependency array means that the code inside our useEffect will run only once, at first render.

Once we get the response, we change the value of the text variable from “Data has not been fetched yet!” to the response data. Thus we can see that the AJAX request has been made successfully.

My Personal Notes arrow_drop_up
Last Updated : 04 Mar, 2022
Like Article
Save Article
Similar Reads
Related Tutorials