React : How to Create Services and Consume in Components with Examples

Services in React are used to manage state and perform side-effects outside of the component lifecycle. They are essential for breaking down complex logic into separate, reusable components that can be shared across different parts of the application. There are two types of services in React – singleton and non-singleton. Singleton services are services that…

By.

min read

Services in React are used to manage state and perform side-effects outside of the component lifecycle. They are essential for breaking down complex logic into separate, reusable components that can be shared across different parts of the application. There are two types of services in React – singleton and non-singleton.

Singleton services are services that have only one instance throughout the lifetime of the application. This means that whenever the service is invoked, it uses the same instance and data. An example of a singleton service in a React application could be an authentication service that manages the state of the current user.

On the other hand, non-singleton services are services that are re-created every time they are invoked. This means that every time the service is used, it has its own instance and data. An example of a non-singleton service in a React application could be a shopping cart service that manages the state of the items added to the cart by the user.

Creating services in React is relatively straightforward. You simply create a JavaScript file, import it into your component, and then call the functions you need. This way, you can keep your component code clean and focused on rendering, and leave the complex logic to the service.

 

How singleton and non-singleton services are different?

It depends on the implementation of the service. If the service is defined as a singleton and only one instance of the service is created and shared among all the components, then it will be a singleton service. If a new instance of the service is created every time a component uses it, then it will not be a singleton service. To create a singleton service in a React app, you can use a design pattern such as the Singleton pattern or the Provider pattern. We will discuss these two with examples going forward.

 

Example of Singleton Service

A singleton service is a service that is instantiated only once throughout the lifetime of an application. This means that all components in the application that use this service will use the same instance of the service, so changes made to the service state by one component will be reflected in other components that use the same instance of the service.

Here’s an example of a singleton service for a counter in React:

import React, { useState } from 'react';

const CounterService = (function () {
  let instance;

  function createInstance() {
    const [count, setCount] = useState(0);

    return {
      count,
      setCount,
      increment: () => setCount(count + 1),
      decrement: () => setCount(count - 1),
    };
  }

  return {
    getInstance: function () {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    },
  };
})();

export default CounterService;

In this example, the CounterService is implemented as a singleton using the Singleton pattern. The getInstance method returns the single instance of the service, and the createInstance method is used to create the instance if it doesn’t already exist.

 

Example of Non-Singleton Service

On the other hand, a non-singleton service is a service that is instantiated every time it’s used by a component. This means that each component that uses the service will have its own instance of the service, so changes made to the service state by one component will not be reflected in other components.

Here’s an example of a non-singleton service for a counter in React:

import React, { useState } from 'react';

function CounterService() {
  const [count, setCount] = useState(0);

  return {
    count,
    setCount,
    increment: () => setCount(count + 1),
    decrement: () => setCount(count - 1),
  };
}

export default CounterService;

In this example, the CounterService is implemented as a non-singleton service. Each component that uses the service will have its own instance of the service, so changes made to the service state by one component will not be reflected in other components.

 

How to use these services in component?

You can use a react service in components as shown below:

import React, { useState, useEffect } from 'react';
import counterService from './counterService';

const Counter = () => {
    const [count, setCount] = useState(0);
    const service = counterService();
    
    useEffect(() => {
        setCount(service.getCount());
    }, [service]);
    
    return (
        <div>
            <h1>Counter: {count}</h1>
            <button onClick={() => {
                service.increment();
                setCount(service.getCount());
            }}>
                Increment
            </button>
            <button onClick={() => {
                service.decrement();
                setCount(service.getCount());
            }}>
                Decrement
            </button>
            <button onClick={() => {
                service.reset();
                setCount(service.getCount());
            }}>
                Reset
            </button>
        </div>
    );
};

export default Counter;

In this example, the counterService is used to manage the state of the counter, and the React component is used to display the count and handle the button clicks to update the count. The useEffect hook is used to keep the count in the component in sync with the count in the service.

 

Conclusion

Creating services in a React app is an important aspect of software development as it allows developers to separate concerns, promote reusability and make their code more maintainable. Services can either be singleton or non-singleton. Singleton services are instances that are shared across the entire application and only one instance is created. Non-singleton services, on the other hand, create a new instance every time they are used, allowing them to maintain their own state. By using services in React, developers can write clean, organized, and scalable code that is easier to maintain and debug.

Leave a Reply

Your email address will not be published. Required fields are marked *