How to Use Axios in React: Simple Guide with Examples
To use
axios in React, first install it with npm install axios. Then import axios in your component and use it inside useEffect or event handlers to fetch data asynchronously.Syntax
Here is the basic syntax to use axios for a GET request inside a React component:
import axios from 'axios': brings axios into your file.axios.get(url): sends a GET request to the URL..then(response => ...): handles the successful response..catch(error => ...): handles errors if the request fails.
javascript
import axios from 'axios'; axios.get('https://api.example.com/data') .then(response => { // use response.data here }) .catch(error => { // handle error here });
Example
This example shows how to fetch data from an API when the component loads and display it. It uses React's useState to store data and useEffect to run the fetch once.
javascript
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function DataFetcher() { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts/1') .then(response => { setData(response.data); }) .catch(err => { setError('Failed to fetch data'); }); }, []); if (error) return <p>{error}</p>; if (!data) return <p>Loading...</p>; return ( <div> <h1>{data.title}</h1> <p>{data.body}</p> </div> ); } export default DataFetcher;
Output
<h1>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h1>
<p>quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto</p>
Common Pitfalls
Some common mistakes when using axios in React include:
- Not handling errors with
.catch(), which can cause the app to crash silently. - Forgetting to add an empty dependency array
[]inuseEffect, causing repeated requests. - Not updating state properly, leading to no UI update.
- Using
axios.getoutside of React lifecycle or event handlers, causing unexpected behavior.
javascript
/* Wrong: Missing error handling and dependency array */ useEffect(() => { axios.get('https://api.example.com/data') .then(response => { setData(response.data); }); }); /* Right: Proper error handling and dependency array */ useEffect(() => { axios.get('https://api.example.com/data') .then(response => { setData(response.data); }) .catch(error => { setError('Error fetching data'); }); }, []);
Quick Reference
Remember these tips when using axios in React:
- Always import
axiosbefore use. - Use
useEffectwith an empty array to fetch data on mount. - Handle errors with
.catch()to avoid crashes. - Update React state to trigger UI changes.
- Use async/await inside
useEffectif preferred for cleaner code.
Key Takeaways
Install axios with npm and import it in your React component before use.
Use axios inside useEffect with an empty dependency array to fetch data on component load.
Always handle errors with .catch() to prevent app crashes.
Update React state with the fetched data to render it in the UI.
Avoid repeated requests by correctly setting useEffect dependencies.