Dhananjay Kuber

React Design Pattern: Singletone

Design Patterns

Design Patterns are the best practices which are used while designing the software that are scalable, modular, maintainable and etc.

Following are some of the types of design patterns

  1. Singletone
  2. Proxy
  3. Factroy
  4. Observerable
  5. Mixin

Singletone design pattern

  • Singletone design pattern restrict from making multiple objects (instance) of the same class.
  • Let's take a example, In React app we are making connection with our socket server. The component in which we are making socket connection has local state named count. In react when the state changes the whole component will rerenders. So at every rerender the new socket connection will be created. This will end up by creating many socket connection.
  • To solve above problem the Singletone design pattern is used
// SocketService.tsx
class SocketService {
  private static instance: SocketService | null = null;

  private constructor() {
    console.log('Socket Connected');
  }

  public static getInstance(): SocketService {
    if (!SocketService.instance) {
      SocketService.instance = new SocketService();
    }
    return SocketService.instance;
  }

  sendData() {
    console.log('Sending data to socket');
  }
}

export default SocketService;
  • In above SocketService the static method getInstance will be used to get the object (instance) of SocketService class. This method will prevent the multiple object creation of SocketService class.
// App.tsx
import { useState } from 'react';
import SocketService from '../utils/socket';

const App = () => {
  const socket = SocketService.getInstance();

  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Count : {count}</button>
    </div>
  );
};

export default App;
  • In App.tsx if the count state changes still the same connection of socket will be maintained as we get the same object of SocketService using getInstance method

Visual Representation

Singletone Pattern