How to Fetch Data in React js and Next js

Sonjoy Chandra Barman
2 min readDec 27, 2022

--

There are several ways to fetch data in a React application. Here are a few common approaches:

fetch API: The fetch API is a modern way to make HTTP requests. It is built into most modern browsers, and you can use it in your React applications with the following code:

fetch('http://example.com/api/endpoint')
.then(response => response.json())
.then(data => console.log(data))

Axios: Axios is a popular JavaScript library that allows you to make HTTP requests from the browser. You can install it using npm by running npm install axios. Here's an example of how to use it in a React component:

import axios from 'axios';

function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('http://example.com/api/endpoint')
.then(response => setData(response.data))
}, []);
return (
// render data here
);
}

async/await: Another way to make HTTP requests in a React component is to use the async/await syntax. This allows you to write asynchronous code in a way that looks more like synchronous code. Here's an example:

async function MyComponent() {
const response = await fetch('http://example.com/api/endpoint');
const data = await response.json();
console.log(data);
}

Regardless of which approach you to choose, it’s important to remember that data fetching in a React application should generally be done in the useEffect hook, which allows you to perform side effects in a functional component. This ensures that the data is fetched only when the component mounts and not on every render.

--

--

Sonjoy Chandra Barman

I am excited to continue my career as a full-stack developer and am always looking for new challenges and opportunities to grow and learn.