How to Fetch Data in React js and Next js
There are several ways to fetch data in a React application. Here are a few common approaches:
fetch
API: Thefetch
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 theasync
/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.