here’s an example React code that uses fetch() combined with useEffect() to load data from a REST API and display it on the page::-
import React, { useState, useEffect } from “react”;
function App() {
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await fetch(“https://example.com/api/data”);
const json = await response.json();
setData(json);
}
fetchData();
}, []);
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.title}</div>
))}
</div>
);
}
export default App;
In this example, we’re using useState() to create a state variable called data, which we’ll use to store the data that we fetch from the API. We’re also using useEffect() with an empty dependency array to fetch the data when the component mounts for the first time.
Inside the useEffect() hook, we define an async function called fetchData(), which uses fetch() to make a GET request to our API endpoint. We then parse the JSON response using response.json(), and set the data state variable using setData().
In the return statement, we use data.map() to render each item in the data array as a <div> element with the item’s title property as its content.
Note that in a real application, you would probably want to handle errors and loading states, and possibly also use a library like axios instead of fetch() to simplify your API calls.