<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Shreeyash SJ</title>
    <description>The latest articles on Forem by Shreeyash SJ (@shreeyashsj).</description>
    <link>https://forem.com/shreeyashsj</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F953043%2Fe49ae713-0610-47ca-b6cf-d40d577afd3a.jpg</url>
      <title>Forem: Shreeyash SJ</title>
      <link>https://forem.com/shreeyashsj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/shreeyashsj"/>
    <language>en</language>
    <item>
      <title>Exploring the Singleton Pattern: Leveraging a Powerful Design Principle in React</title>
      <dc:creator>Shreeyash SJ</dc:creator>
      <pubDate>Tue, 09 Apr 2024 05:29:46 +0000</pubDate>
      <link>https://forem.com/shreeyashsj/exploring-the-singleton-pattern-leveraging-a-powerful-design-principle-in-react-47do</link>
      <guid>https://forem.com/shreeyashsj/exploring-the-singleton-pattern-leveraging-a-powerful-design-principle-in-react-47do</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Maximising Code Efficiency: Understanding and Implementing the Singleton Pattern in React&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As one of the fundamental design patterns in software engineering, the Singleton pattern offers a powerful solution for managing resources and ensuring that only one instance of a class exists in a system. While many developers are familiar with its basic concept, the Singleton pattern’s application in React and its importance are often overlooked. In this article, we’ll delve into the Singleton pattern, its use cases in React applications, and why developers should consider incorporating it into their projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Understanding the Singleton Pattern&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Singleton pattern is a &lt;strong&gt;creational design pattern&lt;/strong&gt; that restricts the instantiation of a class to a single object. It ensures that no matter how many times the class is instantiated, there’s only one instance of it in the entire application. This singleton instance provides a global point of access to the class’s functionality, making it useful for scenarios where a single shared resource needs to be accessed from multiple parts of the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Implementing the Singleton Pattern&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In React, the Singleton pattern can be implemented using various approaches like modules, custom hooks, or context API. For instance, a singleton.js module exports a single instance of the &lt;strong&gt;Singleton class&lt;/strong&gt;, shared across all parts of the application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj24whb4a51xsqc9lfp49.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj24whb4a51xsqc9lfp49.png" alt="SingletonImg" width="800" height="678"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, the singleton.js module exports a single instance of the singleton class. Whenever this module is imported into other parts of the application, they all share the same instance of the singleton class.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Use Cases for the Singleton Pattern in React&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Imagine developing a multi-step form in a React application where users fill out several sections before submitting details. Each step requires access to the same instance of a data service for handling API requests. The Singleton pattern ensures a single instance of the data service, preventing &lt;strong&gt;redundant initializations&lt;/strong&gt; and **maintaining data consistency **throughout the form-filling process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DataService.js
class DataService {
  constructor() {
    if (!DataService.instance) {
      // Perform initialization logic
      this.data = {}; // Placeholder for form data

      DataService.instance = this;
    }
    return DataService.instance;
  }

  // Method to save form data to the server
  saveFormData(formData) {
    // API request to save form data
    console.log('Saving form data:', formData);
  }
}
export default DataService;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const FormStep = ({ step }) =&amp;gt; {
  const [formData, setFormData] = useState({});
  const dataService = new DataService(); // Singleton instance of DataService

  const handleInputChange = (e) =&amp;gt; {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = () =&amp;gt; {
    // Save form data using the singleton instance of DataService
    dataService.saveFormData(formData);
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Step {step}&amp;lt;/h2&amp;gt;
      &amp;lt;input type="text" name="firstName" placeholder="First Name" onChange={handleInputChange} /&amp;gt;
      &amp;lt;input type="text" name="lastName" placeholder="Last Name" onChange={handleInputChange} /&amp;gt;
      &amp;lt;button onClick={handleSubmit}&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  In this implementation:
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;DataService class&lt;/strong&gt; implements the Singleton pattern by checking if an instance already exists before creating a new one. If no instance exists, it initializes the data service and assigns it to the &lt;strong&gt;DataService.instance&lt;/strong&gt; property.&lt;/p&gt;

&lt;p&gt;Each FormStep component imports the DataService module and creates a new instance using new DataService(). However, since the Singleton pattern ensures that only one instance of DataService exists, all instances created by different components will refer to the same object.&lt;/p&gt;

&lt;p&gt;When a user submits the form data in any step, the handleSubmit function calls the saveFormData method of the Singleton instance of DataService, ensuring that the form data is saved using the same instance across all steps.&lt;/p&gt;

&lt;p&gt;This implementation ensures that the data service is initialized only once and remains consistent throughout the form-filling process, providing a seamless user experience and efficient resource utilization.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why Singleton in React?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Simplified State Management:&lt;/strong&gt; Provides a single access point to shared resources, simplifying global state management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Efficient Data Caching:&lt;/strong&gt; Reduces redundant API calls by centralizing data caching, enhancing application performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resource Optimization:&lt;/strong&gt; Singleton instances manage external resources like WebSocket connections and HTTP clients, ensuring efficient resource utilization and avoiding contention issues.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Enhanced Maintainability:&lt;/strong&gt; Encourages code reuse and encapsulation, facilitating easier maintenance and refactoring of complex codebases.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;In Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Singleton pattern is a powerful design principle offering numerous benefits in React development. By leveraging it, developers can effectively manage global state, cache data, and handle external resources. Whether optimizing performance, simplifying access to shared resources, or improving code maintainability, the Singleton pattern has much to offer React developers. Let’s explore its potential and harness its benefits to build more efficient and scalable React applications.&lt;/p&gt;

&lt;p&gt;If you found this article helpful, please consider giving it a like and sharing it with your fellow developers. Happy coding!&lt;/p&gt;

</description>
      <category>singleton</category>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Exploring the Depths of Axios: Uncovering Lesser-Known Capabilities</title>
      <dc:creator>Shreeyash SJ</dc:creator>
      <pubDate>Fri, 05 Apr 2024 07:34:46 +0000</pubDate>
      <link>https://forem.com/shreeyashsj/exploring-the-depths-of-axios-uncovering-lesser-known-capabilities-1l28</link>
      <guid>https://forem.com/shreeyashsj/exploring-the-depths-of-axios-uncovering-lesser-known-capabilities-1l28</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Exploring the Depths of Axios: Uncovering Lesser-Known Capabilities&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As one of the most popular HTTP client libraries in the JavaScript ecosystem, Axios is renowned for its simplicity, flexibility, and powerful feature set. While many developers are familiar with its basic functionalities, there are several lesser-known features that remain untapped. In this article, we’ll take a deep dive into some of these hidden gems, helping Axios users unlock new capabilities and improve their HTTP request handling workflows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Custom Instance Configuration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you’re developing a multi-environment application that interacts with different API servers. With Axios’s custom instance configuration, you can easily manage these environments by creating custom instances with specific configurations for each environment. For instance, you can set different base URLs or headers depending on whether you’re working on a development, staging, or production environment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a custom Axios instance with specific configuration
import axios from 'axios';

const customAxios = axios.create({
  baseURL: 'https://api.example.com/',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
  }
});

export default customAxios;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By leveraging custom instances, developers can maintain cleaner code organisation and achieve greater flexibility in managing their HTTP requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose you’re building an authentication system for your application. With Axios interceptors, you can seamlessly intercept outgoing requests to add authentication headers before they’re sent to the server. Similarly, you can intercept incoming responses to handle authentication errors and redirect users to the login page if their session expires. Interceptors are powerful middleware functions that allow users to intercept requests or responses before they are handled by Axios.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Adding request interceptor
axios.interceptors.request.use(
  (config) =&amp;gt; {
    // Add custom logic before sending the request
    console.log('Request interceptor triggered:', config);
    return config;
  },
  (error) =&amp;gt; {
    // Handle request error
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// Adding response interceptor
axios.interceptors.response.use(
  (response) =&amp;gt; {
    // Add custom logic after receiving the response
    console.log('Response interceptor triggered:', response);
    return response;
  },
  (error) =&amp;gt; {
    // Handle response error
    console.error('Response error:', error);
    return Promise.reject(error);
  }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With interceptors, developers can implement cross-cutting concerns in a centralized manner, improving code maintainability and reducing duplication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Handling Request Cancellation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine you’re developing a real-time chat application where users can send and receive messages. If a user navigates away from the chat screen while a message is being sent, you don’t want to waste network resources by continuing to send the message. By leveraging Axios’s request cancellation feature, you can cancel the pending request when the user navigates away, ensuring efficient resource utilisation. This feature is particularly valuable in scenarios where users navigate away from a page or perform actions that render ongoing requests obsolete.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Importing Axios library and cancellation token
import axios, { CancelToken } from 'axios';

// Creating a cancellation token
const source = CancelToken.source();

// Making a request with cancellation token
axios.get('/api/data', {
  cancelToken: source.token
}).then((response) =&amp;gt; {
  console.log('Response:', response.data);
}).catch((error) =&amp;gt; {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  } else {
    console.error('Request error:', error);
  }
});

// Canceling the request
source.cancel('Request canceled by the user');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By incorporating request cancellation into their applications, developers can enhance the user experience and optimise resource utilisation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Global Error Handling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose you’re working on an e-commerce application where users frequently encounter network errors or server timeouts. With Axios’s global error handling feature, you can define a centralized error handling logic to gracefully handle these errors. For example, you can display a friendly error message to the user, retry the failed request, or log the error for further analysis.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Adding global error handling interceptor
axios.interceptors.response.use(
  (response) =&amp;gt; {
    return response;
  },
  (error) =&amp;gt; {
    if (error.response) {
      // The request was made and the server responded with a status code
      console.error('Response error:', error.response.status, error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an error
      console.error('Error:', error.message);
    }
    return Promise.reject(error);
  }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With global error handling, developers can ensure consistent error reporting and gracefully handle unexpected situations in their applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, Axios offers a wealth of features beyond its basic functionalities, providing users with powerful tools to streamline their HTTP request handling workflows. By exploring these lesser-known features, developers can unlock new capabilities, improve code quality, and enhance the reliability and performance of their applications. Whether it’s creating custom instances, implementing interceptors, handling request cancellation, or managing errors, Axios empowers users to tackle diverse challenges with ease. Let’s continue to explore and leverage the full potential of this versatile library in our projects.&lt;/p&gt;

&lt;p&gt;If you found this article helpful, please consider giving it a like and sharing it.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>axios</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
