SmartCodingTips

πŸ“¦ useEffect + Axios

Axios is a promise-based HTTP client that's often preferred over fetch due to cleaner syntax and built-in JSON parsing. Here’s how to use it inside useEffect().


πŸ§ͺ Example: Fetch Users with Axios


import React, { useEffect, useState } from 'react';
import axios from 'axios';

function UsersList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(res => {
        setUsers(res.data);
        setError(null);
      })
      .catch(err => {
        setError(err.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default UsersList;
  

πŸ” Axios Benefits

  • No need for JSON.parse() β€” Axios does it automatically
  • Better error messages
  • Supports request/response interceptors
  • Works on both client and server (Node.js)

Install Axios via npm install axios before using it.