DEV Community

K.A.FrontDev
K.A.FrontDev

Posted on • Originally published at kafrontdev.Medium on

Ky: The Lightweight Alternative to Axios for Your React Apps

Post cover
Photo by Douglas Lopes on Unsplash

When building React applications, handling HTTP requests is an essential task. For years, many developers have relied on Axios for its rich feature set and ease of use. However, if you’re looking for a leaner, more modern solution, Ky might just be your new best friend! In this article, we’ll explore why Ky is a great alternative for Axios , share some engaging insights, and dive into real-world TypeScript examples that you can start using today. Let’s get started! 😊

What is Ky?

Ky is a tiny HTTP client based on the browser’s native fetch API. Unlike Axios , which bundles many features that you might not need, Ky focuses on simplicity and modularity. It provides a clean, promise-based API, built-in retries, and timeout support — all while keeping your bundle size small. This makes Ky a fantastic choice for modern React applications where performance and simplicity matter.

Why Choose Ky Over Axios?

1. Lightweight & Modern

Ky is designed to be minimalistic. Because it’s built on top of the native fetch API, it leverages modern browser capabilities and offers a smaller footprint compared to Axios. This means faster load times and a more efficient application, which is crucial for performance-sensitive projects.

2. First-Class TypeScript Support

Ky comes with excellent TypeScript support out of the box. The API is strongly typed, reducing the chance of runtime errors and improving the development experience. With TypeScript, you can enjoy autocomplete and inline documentation that help you write more robust code.

3. Built-in Features

Ky offers a range of built-in features such as:

  • Retries: Automatically retry failed requests with exponential backoff.
  • Timeouts: Easily set a timeout for your requests.
  • Hooks: Customize the request/response lifecycle with hooks to add logging, modify requests, or handle errors.

These features allow you to keep your HTTP logic clean and maintainable without the need for extra libraries.

4. Simpler API

Ky’s API is intuitive and minimalistic. It eliminates the need for extensive configuration and setup. For many common use cases, a few lines of code are all you need to handle HTTP requests elegantly.

Real-World Code Examples with TypeScript

Let’s look at some practical examples to see how you can leverage Ky in your React applications.

Example 1: Basic GET Request

Here’s a simple example of making a GET request to fetch data from an API endpoint:

import ky from 'ky';

const fetchData = async () => {
  try {
    const data = await ky.get('https://api.example.com/data').json();
    console.log('Fetched data:', data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

fetchData();
Enter fullscreen mode Exit fullscreen mode

In this snippet, we use ky.get to make a GET request and chain the .json() method to automatically parse the response as JSON. Error handling is straightforward, making the code both clean and readable.

Example 2: Creating an API Instance with Default Configurations

Ky allows you to create an instance with default settings, similar to Axios instances. This is especially useful when working with multiple endpoints or when you need to set common headers.

import ky from 'ky';

const api = ky.create({
  prefixUrl: 'https://api.example.com/',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN_HERE',
    'Content-Type': 'application/json'
  },
  timeout: 10000, // 10 seconds timeout
});

// Usage in a React component or elsewhere
const getUserData = async () => {
  try {
    const user = await api.get('users/1').json<{ id: number; name: string }>();
    console.log('User data:', user);
  } catch (error) {
    console.error('Error fetching user data:', error);
  }
};

getUserData();
Enter fullscreen mode Exit fullscreen mode

By using ky.create, we define a base URL and default headers, so each request automatically inherits these settings. Notice how TypeScript helps us enforce the expected structure of the response with generics.

Example 3: POST Request with TypeScript

Handling POST requests is just as straightforward. Here’s how you can send data with a POST request and type the response:

interface NewUser {
  name: string;
  email: string;
}

interface CreatedUser extends NewUser {
  id: number;
}

const createUser = async (user: NewUser): Promise<CreatedUser> => {
  try {
    const createdUser = await api.post('users', {
      json: user,
    }).json<CreatedUser>();

    console.log('Created user:', createdUser);
    return createdUser;
  } catch (error) {
    console.error('Error creating user:', error);
    throw error;
  }
};

createUser({ name: 'Jane Doe', email: 'jane.doe@example.com' });
Enter fullscreen mode Exit fullscreen mode

This example demonstrates sending JSON data with a POST request. TypeScript ensures that both the input and output types are as expected, making the integration more robust.

Conclusion

Ky brings a refreshing, modern approach to making HTTP requests in your React applications. With its lightweight design, excellent TypeScript support, and a simplified API, Ky provides a compelling alternative to Axios. Whether you’re building a small project or a large-scale application, giving Ky a try can lead to cleaner, more efficient code — and that’s always a win! 🎉

If you haven’t already, give Ky a spin in your next React project and experience the benefits firsthand. Happy coding! 😎

Top comments (0)