DEV Community

Cover image for Implementation of Singleton Design Pattern in React
Nashir Jamali
Nashir Jamali

Posted on

Implementation of Singleton Design Pattern in React

Introduction:

The Singleton Pattern is one of the 23 patterns described in the book Design Patterns: Elements of Reusable Object-Oriented Software (1994) by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (known as the "Gang of Four"). The main purpose of the Singleton Pattern is to limit the creation of multiple instances in several classes by creating an instance in a new class that can be accessed globally.

Objectives and Benefits:

  1. Consistency: By using the Singleton pattern, you can ensure that there is only one instance of a particular object, such as API configuration or application settings, used throughout the application. This helps maintain consistency and avoids conflicts that may arise if multiple instances exist.

  2. Resource Management: The Singleton pattern is also useful in resource management, such as database connections or configuration settings, where only one instance is required. This ensures efficient use of resources and simplifies the management of shared resources across the application.

Example of Implementing Singleton in React with Axios

Here is an example of implementing the Singleton Pattern in React using Axios for API configuration:

1. Create an Axios Instance

Create a new file named axiosInstance.ts to configure the Axios instance:

// axiosInstance.ts
import axios from 'axios';

const axiosInstance = axios.create({
    baseURL: 'https://api.example.com', // Replace with your API base URL
    timeout: 1000, // Set a timeout for requests
    headers: {
        'Content-Type': 'application/json',
    },
});

// Optional: Add interceptors for request/response handling
axiosInstance.interceptors.request.use(
    (config) => {
        // You can add authorization tokens or other configurations here
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

axiosInstance.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        // Handle errors globally
        return Promise.reject(error);
    }
);

export default axiosInstance;
Enter fullscreen mode Exit fullscreen mode

2. Use the Axios Instance in Your Components

Now you can use this Axios instance in your React components to make API calls:

// ExampleComponent.tsx
import React, { useEffect, useState } from 'react';
import axiosInstance from './axiosInstance';

const ExampleComponent: React.FC = () => {
    const [data, setData] = useState<any>(null);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axiosInstance.get('/endpoint'); // Replace with your API endpoint
                setData(response.data);
            } catch (err) {
                setError(err.message);
            }
        };

        fetchData();
    }, []);

    return (
        <div>
            {error && <p>Error: {error}</p>}
            {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>Loading...</p>}
        </div>
    );
};

export default ExampleComponent;
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Creating the Axios Instance: In axiosInstance.ts, we create a single instance of Axios with a base URL and optional interceptors for handling requests and responses.
  • Using the Instance: In ExampleComponent.tsx, we import the Axios instance and use it to fetch data from an API endpoint. The component handles loading states and errors appropriately.

This approach ensures that you have a single, consistent Axios instance throughout your application, following the Singleton pattern.

Conclusion

The implementation of the Singleton Design Pattern in React, especially in the context of API configuration using Axios, offers numerous benefits, including consistency, better resource management, and easy global access. By using this pattern, you can ensure that your application remains organized and efficient while avoiding issues that may arise from the creation of multiple instances.

By understanding and applying the Singleton Pattern in the development of React applications, you can enhance the maintainability and scalability of your code, leading to a more robust application architecture. This approach not only streamlines your API interactions but also contributes to a cleaner and more manageable codebase.

...

Thank you for reading through this article! If you enjoyed it, I would love for you to follow me for more content.

Your feedback and comments are always appreciated, so feel free to share your insights. Thank you for your interest and support!

Top comments (0)