<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nirbhay kumar on Medium]]></title>
        <description><![CDATA[Stories by Nirbhay kumar on Medium]]></description>
        <link>https://medium.com/@nirbhaykumar5572?source=rss-da124e7601a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s2W5FTuycObVJcO6DRsBfg.jpeg</url>
            <title>Stories by Nirbhay kumar on Medium</title>
            <link>https://medium.com/@nirbhaykumar5572?source=rss-da124e7601a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:29:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nirbhaykumar5572/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Technologies To Build Microservices Architecture]]></title>
            <link>https://medium.com/bitsrc/technologies-to-build-microservices-architecture-f146c3ef8836?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f146c3ef8836</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 17:56:32 GMT</pubDate>
            <atom:updated>2023-10-26T17:56:32.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d9H575KklInkHzPc" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Microservices are on the rise in the market, with businesses increasingly adopting them to construct more complex and sizable applications that can be compartmentalized into a collection of smaller services. There’s a growing number of individuals seeking to transform their traditional monolithic systems into a sequence of independent microservices.</p><p>A common question that naturally arises is: Which programming language is most suitable for developing microservices in your upcoming project?</p><p>Your choice of technology should be driven by the specific requirements of your microservices. It’s important to consider various factors when selecting a programming language. Microservices architecture offers flexibility, but an excessive variety of programming languages can introduce operational complexity. To streamline your technology stack, evaluate programming languages based on the following criteria:</p><ol><li>Observability: Opt for a language that provides robust monitoring and debugging tools for your microservices.</li><li>Automation Support: Choose a language that facilitates automation in deployment and scaling.</li><li>User-Centric Approach: Prioritize a language that enhances the user experience for consumers of your microservices.</li><li>Independent Deployment: Ensure that each microservice can be deployed autonomously.</li><li>Alignment with Business Domain: Select a language that seamlessly aligns with your business requirements.</li><li>Decentralization of Components: Confirm that the language supports decentralized components, avoiding bottlenecks.</li><li>Continuous Integration Support: Your chosen language should integrate seamlessly into your CI/CD pipeline.</li></ol><p>Now, let’s explore some commonly used programming languages for developing microservices:</p><p>1. Java: Java is a popular choice for microservices due to its readable annotation syntax, which is particularly beneficial in complex systems. Java offers various features for developing and deploying microservices. It supports Java EE standards such as JAX-RS, JPA, and CDI, making it well-suited for microservices development. Notable frameworks like Spring Boot, Dropwizard, Restlet, and Spark provide solid support for Java-based microservices.</p><p>2. Golang (Go): Go is renowned for its robust concurrency support and is an excellent choice for microservices development. Its concurrency capabilities enhance productivity on multicore machines. Go offers two prominent frameworks: GoMicro and Go Kit, both excelling in simplicity and robust testing support.</p><p>3. Python: Python, a high-level language, is known for its integration capabilities. It’s valued for rapid prototyping and boasts various frameworks like Flask, Falcon, Bottle, Nameko, and CherryPy that are well-suited for microservices development.</p><p>4. Node.js: Node.js is an excellent choice for handling IO-bound tasks, known for its speed in IO-bound operations. It is particularly efficient for applications relying on CPU-bound or IO-bound code.</p><p>Each of these languages has unique strengths and can be a suitable choice for microservices development, depending on your project’s specific needs and your development team’s expertise. By considering the criteria mentioned earlier, you can make an informed choice that best aligns with your business goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f146c3ef8836" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/technologies-to-build-microservices-architecture-f146c3ef8836">Technologies To Build Microservices Architecture</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Microservices: Revolutionizing Modern Software Architecture]]></title>
            <link>https://blog.devgenius.io/an-introduction-to-microservices-revolutionizing-modern-software-architecture-5cf7cd3ba581?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf7cd3ba581</guid>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 13:06:31 GMT</pubDate>
            <atom:updated>2023-07-03T10:00:29.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJibMqEwuxJ8Pg366pq94Q.jpeg" /></figure><blockquote>In the world of software development, traditional monolithic architectures are being replaced by a more flexible and scalable approach known as microservices. Microservices have gained popularity for their ability to enhance agility, scalability, and resilience in modern applications. This blog post aims to provide a comprehensive overview of microservices, exploring their key concepts, benefits, challenges, and best practices.</blockquote><p>Table of Contents:</p><ol><li>What are Microservices?</li><li>Key Concepts of Microservices</li><li>Benefits of Microservices</li><li>Challenges of Microservices</li><li>Best Practices for Microservices</li><li>Use Cases and Success Stories</li><li>Conclusion</li></ol><blockquote><strong>1. What are Microservices?</strong></blockquote><p>Microservices are small, independent services that work together to form a complete application. They replace monolithic architectures and enable modular development and deployment.</p><p>In a microservices architecture, each service is responsible for a specific function or feature of the application. Services communicate with each other through well-defined APIs, often using lightweight protocols such as HTTP or message queues. This decoupled nature allows services to be developed, deployed, and scaled independently, providing flexibility and agility.</p><blockquote><strong>2. Key Concepts of Microservices:</strong></blockquote><p>a. Service Independence and Single Responsibility: Each microservice has a single responsibility or function, representing a specific business capability. This separation of concerns enables individual services to evolve independently, facilitating parallel development and deployment.</p><p>b. Communication and Interoperability: Microservices communicate with each other through well-defined APIs. They can use different communication patterns, such as synchronous HTTP requests or asynchronous messaging with message queues. This loose coupling ensures interoperability and allows services to be developed using different technologies and programming languages.</p><p>c. Decentralized Data Management: In a microservices architecture, each service manages its own data and database. This approach promotes autonomy and reduces dependencies between services. It also enables the use of different database technologies, tailored to the specific needs of each service.</p><p>d. Containerization and Orchestration: Microservices are often deployed in containers, such as Docker, to provide consistency and portability across different environments. Container orchestration tools like Kubernetes help manage the deployment, scaling, and monitoring of microservices, ensuring high availability and resilience.</p><blockquote><strong>3. Benefits of Microservices:</strong></blockquote><p>a. Scalability and Elasticity: Microservices enable horizontal scaling, allowing individual components to scale independently based on their specific workload. This ensures efficient resource utilization and the ability to handle varying levels of demand.</p><p>b. Agility and Continuous Deployment: With microservices, small cross-functional teams can independently develop, test, and deploy their services. This promotes faster iterations and continuous delivery of new features, enabling businesses to respond quickly to market needs.</p><p>c. Technology Heterogeneity: Microservices architecture allows the use of different technologies and programming languages within an application. This flexibility empowers teams to choose the most suitable tools for each service, fostering innovation and leveraging the strengths of various technologies.</p><p>d. Fault Isolation and Resilience: Microservices are designed to be resilient to failures. If one service encounters an issue, it does not affect the entire system. Failures are isolated, ensuring that the overall system remains available and responsive.</p><p>e. Team Autonomy and Productivity: By dividing an application into microservices, teams can work autonomously on different services. This improves productivity by enabling teams to focus on their specific areas of expertise without being slowed down by dependencies on other teams.</p><blockquote><strong>4. Challenges of Microservices:</strong></blockquote><p>a. Distributed System Complexity: Microservices introduce complexities related to distributed system design. Communication, data consistency, fault tolerance, and maintaining the overall system’s integrity require careful consideration and implementation.</p><p>b. Service Coordination and Choreography: Coordinating interactions between microservices can be challenging. Services must follow proper choreography or orchestration patterns to ensure synchronization and avoid data inconsistencies.</p><p>c. Data Consistency and Integrity: Maintaining data consistency across multiple microservices can be complex. Strategies such as distributed transactions, eventual consistency, and event-driven architectures need to be carefully implemented to ensure data integrity.</p><p>d. Operational Overhead: Deploying and managing a large number of microservices requires robust infrastructure, automated deployment processes, and effective monitoring and logging strategies. The operational overhead can be significant, requiring expertise in managing distributed systems.</p><p>e. Service Discovery and Monitoring: Discovering and tracking the health and performance of multiple microservices is crucial for maintaining a reliable system. Service discovery mechanisms and comprehensive monitoring solutions are essential to identify and address issues promptly.</p><blockquote><strong>5. Best Practices for Microservices:</strong></blockquote><p>a. Design for Failure and Resilience: Expect and handle failures gracefully by implementing fallback mechanisms, retries, and circuit breakers. Build fault tolerance into the design of each microservice.</p><p>b. Maintain Strong Service Boundaries: Clearly define service boundaries to minimize dependencies and ensure encapsulation. Use well-defined APIs and contracts to communicate between services.</p><p>c. Embrace Decentralized Data Management: Each microservice should have its own database or data store, managing its data independently. Choose appropriate data storage technologies based on the specific requirements of each service.</p><p>d. Automate Deployment and Testing: Use Continuous Integration and Continuous Deployment (CI/CD) pipelines to automate the deployment and testing processes. Implement automated testing, including unit tests, integration tests, and end-to-end tests.</p><p>e. Monitor and Analyze Performance: Implement robust monitoring and logging solutions to gain insights into the health, performance, and usage patterns of microservices. Use tools for centralized logging, distributed tracing, and metrics collection to identify bottlenecks and optimize performance.</p><blockquote><strong>6. Use Cases of Microservices:</strong></blockquote><p>a. E-commerce Platforms: Microservices allow e-commerce platforms to scale different functionalities independently, such as inventory management, order processing, payment processing, and recommendation systems.</p><p>b. Social Media Applications: Social media platforms leverage microservices to handle various features like user authentication, feed generation, notifications, messaging, and content moderation.</p><p>c. Financial Services: Microservices enable financial institutions to build secure and scalable applications for services like account management, payments, fraud detection, and risk analysis.</p><p>d. Travel and Hospitality: Travel and hospitality companies utilize microservices for features such as booking management, flight search and reservation, hotel availability, and loyalty programs.</p><blockquote><strong>7. Success Stories:</strong></blockquote><p>a. Netflix: Netflix moved from a monolithic architecture to microservices, allowing them to scale and evolve rapidly. Microservices enabled features like personalized recommendations, streaming, user profiles, and content management.</p><p>b. Uber: Uber’s microservices architecture supports real-time ride tracking, pricing calculations, driver dispatching, payment processing, and analytics, facilitating millions of rides daily.</p><p>c. Airbnb: Airbnb’s platform relies on microservices to handle listings, bookings, search functionality, payment processing, messaging, and reviews, providing a seamless user experience</p><blockquote><strong>Conclusion:</strong></blockquote><p>Microservices offer numerous benefits for modern software development, including scalability, agility, and resilience. By understanding their key concepts, addressing challenges, and following best practices, developers can leverage microservices to build scalable and flexible applications in today’s fast-paced digital landscape. While microservices introduce complexities, the rewards of improved scalability, faster development cycles, and efficient resource utilization make them a powerful architectural approach for modern software systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf7cd3ba581" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/an-introduction-to-microservices-revolutionizing-modern-software-architecture-5cf7cd3ba581">An Introduction to Microservices: Revolutionizing Modern Software Architecture</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding *args and **kwargs in Python: Simplifying Function Parameters]]></title>
            <link>https://blog.devgenius.io/understanding-args-and-kwargs-in-python-simplifying-function-parameters-de4de401b5e7?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4de401b5e7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[args-and-kwargs]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 13:14:52 GMT</pubDate>
            <atom:updated>2023-08-21T09:04:30.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQz8LmwzY4YaeXD2td-IBQ.jpeg" /><figcaption>Image creadit — CloudSigma</figcaption></figure><blockquote>I was working on developing a python library and I got a need to implement variable number of args and key value pairs. I code in JavaScript most of the time, where de-structuring feature allows this. Here I made an attempt to make you understand about something similar feature in python.</blockquote><h3>Introduction</h3><p>Python is a versatile and expressive programming language that offers powerful features to make code concise and flexible. One such feature is the ability to use *args and **kwargs in function definitions. These special syntaxes allow us to handle an arbitrary number of arguments, making our code more dynamic and adaptable. In this blog post, we will explore *args and **kwargs in detail, understand how they work, and see practical examples of their usage.</p><h3>Understanding *args</h3><p>The *args syntax in a function definition allows the function to accept a variable number of positional arguments. It collects these arguments into a tuple, which can be accessed within the function body. Let&#39;s see an example to better understand *args:</p><pre>def concatenate_strings(*args):<br>    result = &#39;&#39;<br>    for arg in args:<br>        result += arg<br>    return result<br><br>print(concatenate_strings(&#39;Hello&#39;, &#39;, &#39;, &#39;World!&#39;))</pre><p>Output:</p><pre>Hello, World!</pre><p>In the example above, the concatenate_strings function accepts any number of string arguments. The *args parameter collects all the positional arguments into a tuple called args. We can then iterate over args and concatenate all the strings together, returning the final result.</p><h3>Leveraging **kwargs</h3><p>Similar to *args, **kwargs provides a way to handle a variable number of keyword arguments in a function. Instead of collecting the arguments into a tuple, **kwargs packs them into a dictionary, where the keys represent the argument names and the values represent their corresponding values. Consider the following example:</p><pre>def print_student_info(**kwargs):<br>    for key, value in kwargs.items():<br>        print(f&quot;{key}: {value}&quot;)<br><br>print_student_info(name=&#39;John Doe&#39;, age=25, major=&#39;Computer Science&#39;)</pre><p>Output:</p><pre>name: John Doe<br>age: 25<br>major: Computer Science</pre><p>In the above example, the print_student_info function accepts any number of keyword arguments. The **kwargs parameter collects these arguments into a dictionary called kwargs. We can then iterate over the dictionary and print each key-value pair to display the student&#39;s information.</p><h3>Combining *args and **kwargs</h3><p>One of the powerful aspects of Python is that we can combine *args and **kwargs in a single function definition, allowing for even greater flexibility. Let&#39;s take a look at an example:</p><pre>def process_data(*args, **kwargs):<br>    for arg in args:<br>        print(f&quot;Positional argument: {arg}&quot;)<br>    <br>    for key, value in kwargs.items():<br>        print(f&quot;Keyword argument - {key}: {value}&quot;)<br><br>process_data(&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, category=&#39;fruit&#39;, color=&#39;yellow&#39;)</pre><p>Output:</p><pre>Positional argument: apple<br>Positional argument: banana<br>Positional argument: orange<br>Keyword argument - category: fruit<br>Keyword argument - color: yellow</pre><p>In the above example, the process_data function accepts both positional arguments through *args and keyword arguments through **kwargs. We can use the positional arguments in a loop, and the keyword arguments can be accessed as a dictionary, allowing us to perform different operations based on the argument types.</p><h3>Conclusion</h3><p>Understanding *args and **kwargs in Python opens up new possibilities for creating flexible and reusable code. By leveraging these features, we can write functions that accept a varying number of arguments, making our code more adaptable to different scenarios. Whether you need to concatenate strings, process data, or handle a diverse set of inputs, *args and **kwargs provide a powerful mechanism to simplify your function parameters.</p><p>In this blog post, we explored the basics of *args and **kwargs and demonstrated their usage with practical examples. Armed with this knowledge, you can now apply these techniques to your own Python projects, enhancing the versatility and flexibility of your code.</p><p>Thanks for reading, hope it helped…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4de401b5e7" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-args-and-kwargs-in-python-simplifying-function-parameters-de4de401b5e7">Understanding *args and **kwargs in Python: Simplifying Function Parameters</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Functions and Cron Jobs for Efficient Task Scheduling]]></title>
            <link>https://medium.com/bitsrc/unleashing-the-power-of-automation-exploring-serverless-functions-and-cron-jobs-for-efficient-task-cffa07c11bd6?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffa07c11bd6</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cronjob-scheduler]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[cronjob]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 04:08:30 GMT</pubDate>
            <atom:updated>2023-06-14T10:10:03.691Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unleashing the Power of Automation: Exploring Serverless Functions and Cron Jobs for Efficient Task Scheduling</h3><h4>How serverless functions can be utilized to perform specific tasks, and how cron jobs can be scheduled to trigger functions at predefined intervals.</h4><blockquote>I was asked to add couple of fields and change some existing fields in the invoice that will be generated after payment and also make a template generator for handling various emails that has be send to client based on some logic. While going through the codebase, I case across many new concepts like, Serverless functions, cron jobs, schedulers etc. Here is attempt to make you understand about the same, its really interesting.</blockquote><h3><strong>Serverless Functions:</strong></h3><p>Serverless functions, also known as Function-as-a-Service (FaaS), are a cloud computing paradigm where developers can write and deploy individual functions that are executed in a serverless environment. Here are some key aspects of serverless functions:</p><ol><li>Event-driven execution: Serverless functions are triggered by specific events or requests, such as an HTTP request, database update, file upload, or a scheduled time. When the defined trigger occurs, the function is invoked and executed to perform its designated task.</li><li>Scalability and elasticity: Serverless platforms automatically scale the number of instances needed to handle the incoming workload. Functions can scale from handling a few requests to thousands or more, ensuring high availability and performance. The cloud provider manages the infrastructure and resource allocation, allowing developers to focus solely on writing the function code.</li><li>Stateless and ephemeral: Serverless functions are designed to be stateless, meaning they don’t maintain any internal state between invocations. Each function execution is isolated, and any necessary data or context is typically provided through input parameters or external services (e.g., databases or APIs). The functions are short-lived and terminate after completing their tasks, enabling efficient resource utilization.</li><li>Pay-per-use pricing model: With serverless functions, you only pay for the actual usage of your functions, rather than paying for continuously running servers. Billing is typically based on the number of function invocations, execution time, and any additional resources utilized during execution, such as memory, network transfers, or storage.</li><li>Language and platform flexibility: Serverless platforms support various programming languages, enabling developers to choose the language they are most comfortable with. Popular serverless platforms include AWS Lambda, Azure Functions, Google Cloud Functions, and IBM Cloud Functions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*3JDOli47Nxd5LZW_-gJRoA.png" /><figcaption>Image from Amazon AWS</figcaption></figure><blockquote>Serverless functions are commonly used for various purposes, such as building API endpoints, processing events and messages, performing data transformations, executing background jobs, and integrating with external services. They offer benefits like reduced operational overhead, improved scalability, and cost optimization.</blockquote><p><strong>Example of serverless function:</strong></p><p>In this example, we’ll create a serverless function that calculates the square of a given number.</p><pre>// Example of a serverless function (AWS Lambda)<br>exports.handler = async (event, context) =&gt; {<br>  const number = event.number;<br>  const square = number ** 2;<br><br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({ result: square }),<br>  };<br>};</pre><blockquote>In this code snippet, we define an AWS Lambda function. It takes an input number from the event parameter, calculates its square, and returns the result as a JSON response.</blockquote><p><strong>Cron jobs:</strong></p><p>Cron jobs, also known as cron tasks or cron jobs scheduler, are a time-based job scheduling mechanism commonly found in Unix-like operating systems. They allow you to schedule and automate the execution of specific tasks or scripts at predefined intervals. Here are the key aspects of cron jobs:</p><ol><li>Time-based scheduling: Cron jobs are scheduled based on a predefined time or interval specified using a cron expression. The cron expression consists of fields that define the timing pattern for the job. For example, you can schedule a job to run every hour, every day at a specific time, or even more complex schedules.</li><li>Repetitive and recurring tasks: Cron jobs are typically used for automating repetitive tasks that need to be executed on a regular basis. This can include tasks like backups, data synchronization, report generation, system maintenance, or any other activity that needs to occur at specific intervals.</li><li>System-level scheduling: Cron jobs are managed and executed by the operating system’s cron daemon or scheduler. The cron daemon reads the cron table, which contains the list of scheduled jobs and their respective commands or scripts. When a job’s scheduled time is reached, the cron daemon invokes the associated command or script to execute the task.</li><li>Logging and notification: Cron jobs often have logging mechanisms to capture the output or errors generated during their execution. Additionally, email notifications can be set up to alert administrators or users about the status of the job, allowing them to monitor and troubleshoot any issues.</li><li>Integration with serverless platforms: In the context of serverless platforms, cron jobs can be implemented by scheduling the execution of serverless functions at specific intervals</li></ol><blockquote>Combining the power of serverless functions and the scheduling capabilities of cron jobs allows you to automate tasks efficiently and scale based on demand. By leveraging serverless platforms’ managed infrastructure, you can focus on writing the task logic without worrying about server provisioning, scalability, or maintenance. This approach provides a flexible, cost-effective, and scalable solution for executing scheduled tasks in a serverless environment.</blockquote><p><strong>Example of a Cron Job using AWS Lambda and CloudWatch Events:</strong></p><p>In this example, we’ll schedule a cron job using AWS Lambda and CloudWatch Events to trigger a function every day at a specific time.</p><ol><li>First, create an AWS Lambda function that logs a message when triggered:</li></ol><pre>// Example of a cron job using AWS Lambda and CloudWatch Events<br>exports.handler = async (event, context) =&gt; {<br>  console.log(&quot;Cron job triggered at:&quot;, new Date().toISOString());<br><br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({ message: &quot;Cron job executed successfully&quot; }),<br>  };<br>};</pre><p>2. Next, set up a CloudWatch Events rule to trigger the Lambda function:</p><ul><li>Open the AWS CloudWatch console and navigate to “Events” -&gt; “Rules”.</li><li>Click on “Create rule” and configure the rule:</li><li>Under “Event Source”, select “Schedule” and specify the desired cron expression (e.g., cron(0 10 * * ? *) to run every day at 10:00 AM UTC).</li><li>Under “Targets”, select “Lambda function” and choose the Lambda function you created earlier.</li><li>Click on “Configure details” and provide a name and description for the rule.</li><li>Finally, click on “Create rule” to create the cron job.</li></ul><p>Now, the Lambda function will be triggered automatically based on the specified cron expression, executing the code and logging a message at the scheduled time.</p><p>These examples showcase the practical implementation of a serverless function and a cron job using AWS Lambda. They demonstrate how serverless functions can be utilized to perform specific tasks, and how cron jobs can be scheduled to trigger functions automatically at predefined intervals.</p><h3>Build Apps with reusable components, just like Lego</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*13SrcnEYHY_hfKgm.png" /></figure><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h3>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h3><h3>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h3><h3>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h3><h3>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h3><h3>Learn more:</h3><ul><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></li><li><a href="https://blog.bitsrc.io/5-ways-to-build-a-react-monorepo-a294b6c5b0ac">5 Ways to Build a React Monorepo</a></li><li><a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">How to Create a Composable React App with Bit</a></li><li><a href="https://itnext.io/how-to-reuse-and-share-react-components-in-2023-a-step-by-step-guide-85642e543afa">How to Reuse and Share React Components in 2023: A Step-by-Step Guide</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-building-react-component-libraries-in-2023-d8fb8e4c13b4">5 Tools for Building React Component Libraries in 2023</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffa07c11bd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/unleashing-the-power-of-automation-exploring-serverless-functions-and-cron-jobs-for-efficient-task-cffa07c11bd6">Serverless Functions and Cron Jobs for Efficient Task Scheduling</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How big an optimization can be ? Optimizations in React !]]></title>
            <link>https://nirbhaykumar5572.medium.com/how-big-an-optimization-can-be-optimizations-in-react-7544f70780b5?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7544f70780b5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 10:03:59 GMT</pubDate>
            <atom:updated>2023-06-01T10:03:59.242Z</atom:updated>
            <content:encoded><![CDATA[<h3>How big an optimization can be ? Optimizations in React !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*qu4Fg1JKBNNeldmuIKCGxA.png" /></figure><blockquote>Would you call this to be an optimized code, lets listen the situation….</blockquote><p>I was working as as intern in a startup company where I was asked to reduce the size of images taken from the WebCam in react while taking photos ( its part of product ). Since, the photos were of some written docs and other important details, but not all were required to be in HD. Imagine, in FHD, each image on an average takes 3–4 MB, and if we the product has users around 20K ( which is very normal ) and each user has to take 8 images.</p><blockquote>Total size = 8*4 * 20 K MB = 640 K MB = 640 GB…wait, that’s huge. It would cost way more than required.</blockquote><p>Ways to optimize this :</p><ol><li>Take FHD image and then process if further to reduce the size of image and store……<em>it rather adds more processing and CPU usage !</em></li><li>Why not to take the image itself in low quality, if very minute details don’t matter………………….exactly, this is what I did.</li></ol><p>I simply created an dynamic WebCam pixel density as per different states using <em>useState</em> react hook !</p><pre>  const defaultVideoconstraints = {<br>    width: 500,<br>    height: 550,<br>    facingMode: facingMode,<br>  };<br>  const HighQualityVideoConstraints = {<br>    width: 1080,<br>    height: 1920,<br>    facingMode: facingMode,<br>  };<br>  titles = [&quot;heading first&quot;, &quot;heading-second&quot;];<br>  const [videoConstraints, setvideoConstraints] = useState( defaultVideoconstraints );<br><br>  // here index changes by some other code in the application<br>  useEffect(() =&gt; {<br>    // useEffect to run this function whenever index as a dependency changes<br>    const WebHeading = titles[index];<br>    const dependencyArray = [&quot;heading first&quot;];<br>    // if our state is the one which includes &quot;heading first&quot;, the photo taken will be in HD<br>    // else low density<br>    if( dependencyArray.includes( WebHeading ) ) setvideoConstraints( HighQualityVideoConstraints );<br>    else setvideoConstraints( defaultVideoconstraints );<br><br>  }, [ index ]);<br><br><br>// some other code <br><br><br>&lt;div className=&quot;webcam-img&quot;&gt;<br>     {image == &quot;&quot; ? (<br>      &lt;Webcam<br>            audio={ false }<br>            ref={ webcamRef }<br>            screenshotFormat=&quot;image/jpeg&quot;<br>            videoConstraints={ videoConstraints }<br>            onClick={ handleclick }<br>       /&gt;   <br>      ) : &lt; pic/&gt;<br>    }<br>/&gt;<br></pre><blockquote>Lets say, new pixel density is such that the image size is around 10KB, new storage space for those :<br>Total size = 8*10* 20 K KB= 1600 K KB = 1.6 GB…..yayyyyy, that’s actually way to less compared to previous approach!!</blockquote><p>Now the question comes ?? Is this an optimization……I am leaving this onto you, how you define it, but do think that we ended up reducing the storage by 400 times !</p><blockquote>Optimizations need not be only with respect to the optimized code you write, sometimes, they also hidden in the logic of implementing the application.</blockquote><p>Here we will be talking about code optimizations over logical and flow oriented optimizations. Optimizing code in React is crucial for improving the performance and efficiency of your application.</p><blockquote>We will only see the functions and their theory, for proper understanding how do they work in optimizing, please refer the second blog I wrote.</blockquote><ol><li><em>Memoization</em> with React.memo(): U<em>se React.memo(</em>) to memoize functional components and prevent unnecessary re-renders when their props haven’t changed.</li><li>Minimize re-renders: One of the primary goals of optimization in React is to minimize unnecessary re-renders. Ensure that components only update when necessary by utilizing memoization techniques like React.memo(), useCallback(), and useMemo(). These techniques help prevent re-renders when the dependencies haven’t changed.</li><li>Use the <em>useCallback</em>() hook: Memoize event handlers or any other functions that are passed as props to child components using useCallback(). This ensures that the function reference remains the same unless its dependencies change.</li><li>Use the <em>useMemo</em>() hook: Memoize the result of expensive computations using useMemo(). This prevents the calculation from being repeated on every render unless the dependencies change.</li><li>Implement <em>shouldComponentUpdate</em> or <em>PureComponent</em>: For class components, override the shouldComponentUpdate() method or extend PureComponent to perform shallow prop and state comparisons to determine if a re-render is necessary.</li><li>Use the key prop: Provide a unique key prop to each item in a list rendered by the map() function. This helps React efficiently update and reorder the list items without re-rendering all of them.</li><li>Use <em>React’s Context API</em> wisely: Avoid excessive use of context providers or using context at a very high level in the component tree. Consider whether all components consuming the context actually need to update when the context changes.</li><li>Use code splitting and lazy loading: Split your application code into smaller chunks and load them dynamically when needed. This can improve initial load times and reduce the amount of code sent to the browser.</li><li>Virtualize long lists: For large lists, consider using libraries like react-virtualized or react-window to efficiently render only the visible items and recycle DOM nodes as the user scrolls.</li><li>Optimize expensive rendering operations: Identify any expensive operations during rendering, such as heavy computations or deep object comparisons, and optimize or memoize them to minimize their impact on performance.</li><li>Use production builds: When deploying your React application, use production builds that include optimizations like code minification and dead code elimination. This reduces the size of the JavaScript bundle and improves the application’s loading and parsing speed.</li><li>Profile and analyze performance: Use browser developer tools, such as Chrome <em>DevTools</em>, to profile your React application and identify performance bottlenecks. This will help you pinpoint areas that need optimization.</li><li>Use performance testing and benchmarking: Regularly test and benchmark your application’s performance to identify areas that need optimization. Use tools like Lighthouse, WebPageTest, or custom performance testing scripts to measure and analyze performance metrics.</li></ol><p>Please go through the second blog in consecutive to see about these functions implementations. Happy reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7544f70780b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing Magic in React: Building Dynamic Web Applications]]></title>
            <link>https://medium.com/bitsrc/routing-magic-in-react-building-dynamic-web-applications-488344ea4a8a?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/488344ea4a8a</guid>
            <category><![CDATA[dynamic-routing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Mon, 22 May 2023 15:20:40 GMT</pubDate>
            <atom:updated>2023-06-07T05:16:11.813Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn what React Router is and the steps for routing in React.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNCUOx9n7loLgNJzByiO_A.png" /></figure><p>Before you dive into the blog, let me brief you about client and server-side routing.</p><p>Client-side routing and server-side routing are two different approaches to handling navigation within web applications. Here’s a brief explanation of the differences:</p><p>Client-side routing: In client-side routing, the routing logic is handled on the client side (in the browser). When a user clicks on a link or interacts with the application, the routing is managed by JavaScript running on the client side. This means that the entire application code, including all the necessary views and components, is loaded once when the user first accesses the application. Subsequent navigation and rendering of views are handled by JavaScript manipulating the DOM and updating the URL without making a request to the server. This approach provides a smoother and more interactive user experience as it eliminates page refreshes.</p><p>Server-side routing: In server-side routing, the routing logic is handled on the server side. When a user interacts with the application, their request is sent to the server, which determines the appropriate response based on the requested URL. The server renders and returns the HTML content of the requested page. Each time the user navigates to a different page, a new request is made to the server, and the server responds with the corresponding HTML content. This approach results in page refreshes as the entire page is reloaded with each request.</p><p>In summary, client-side routing relies on JavaScript to handle navigation and rendering within the browser, providing a more dynamic and responsive user experience. Server-side routing, on the other hand, involves requesting and rendering new pages from the server for each navigation action, resulting in page refreshes but potentially reducing the complexity on the client side. The choice between client-side and server-side routing depends on factors such as the complexity of the application, performance requirements, SEO considerations, and the desired user experience.</p><h4>Basic Routing</h4><p><strong>React Router API</strong></p><p>React Router is a popular library for handling routing in React applications. It provides a powerful and declarative way to manage the navigation and rendering of different components based on URL paths. React Router helps in building Single Page Applications (SPAs) by enabling client-side routing, where the application can update the UI without causing a full page to reload.</p><p>React Router offers a comprehensive API with various components and utilities:</p><ol><li>&lt;BrowserRouter&gt;: This component provides the routing functionality for the application using HTML5 history API. It ensures that the URL is updated and keeps the UI in sync with the current URL.</li><li>&lt;Route&gt;: The &lt;Route&gt; component is used to define a specific route within the application. It specifies the URL path and the component to be rendered when that route is matched. It can also accept additional props like exact for exact path matching and render for custom rendering logic.</li><li>&lt;Switch&gt;: The &lt;Switch&gt; component is used to wrap multiple &lt;Route&gt; components. It ensures that only the first matching route is rendered. This helps prevent multiple routes from being rendered simultaneously.</li><li>&lt;Link&gt; and &lt;NavLink&gt;: These components are used to create links for navigation within the application. &lt;Link&gt; provides a simple anchor tag for navigation, while &lt;NavLink&gt; adds additional functionality like highlighting the active link based on the current URL.</li><li>URL Parameters: React Router allows you to define dynamic URL parameters in your routes using the :paramName syntax. This allows you to extract values from the URL and pass them as props to the rendered components.</li><li>Nested Routes: React Router supports nested routes, allowing you to create a hierarchy of routes within your application. This is useful for building complex UI structures with multiple levels of nested components.</li><li>Programmatic Navigation: React Router provides a history object that allows you to programmatically navigate to different routes in response to user actions or other events.</li></ol><p>React Router is highly flexible and can be customized to fit the needs of different applications. It supports advanced features like route guarding, route transitions, lazy loading, and more through additional plugins and configuration.</p><blockquote><em>Dont worry, this is just to make you understand of terminologies, hold on….will be explaining you about each of them ✌️✌️ !</em></blockquote><p>There are 3 different packages for React Routing.</p><ol><li><strong>react-router:</strong> It is the heart of react-router and provides core functionalities for routing in web applications and all the packages for react-router- dom and react-router-native</li><li><strong>react-router-native:</strong> It is used for routing in mobile applications</li><li><strong>react-router-dom:</strong> It is used to implement dynamic routing in web applications.</li></ol><blockquote><em>💡</em> Pro Tip: If you want to reuse React components across all your projects, you could consider using an open-source tool like <a href="https://bit.cloud/"><strong>Bit</strong></a>. Bit lets you extract reusable components from your codebase and share it across multiple projects with a simple bit import your.username/yourComponent command.</blockquote><h4>Learn more:</h4><p><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></p><h4>How Routing Works / Routing Mechanism</h4><p>Routing involves navigating between different pages or sections of a website. In the case of client-side rendering with React Router, routing is handled on the client-side rather than relying on the server for each page request.</p><p>With client-side rendering, the server is responsible for providing data, while the rendering and routing logic are executed by the client’s web browser. Unlike traditional routing where the server sends separate HTML files for different pages, client-side rendering with React Router relies on a single index.html file.</p><p>This approach allows for dynamic routing within a single page application (SPA). The client-side JavaScript takes control of rendering different components based on the URL, providing a seamless user experience. The browser’s history API is utilized to enable smooth navigation, including the ability to go forward and backward through the route history. The URL is also updated dynamically to reflect the current route.</p><p>Overall, client-side rendering with React Router offers efficient and responsive routing, enabling a smooth SPA experience with minimal server requests and improved user navigation.</p><h3><strong>Steps for routing in React:</strong></h3><ol><li>Installation for react-router-dom:</li></ol><pre>npm install react-router-dom@6 <br>or <br>yarn add react-router-dom@6 </pre><p>2. Check your <em>package.json </em>file for dependencies for confirmation:</p><pre>{ <br>   &quot;name&quot; : &quot;reactApp&quot;, <br>   &quot;version&quot; : &quot;1.0.0&quot; <br>   &quot;description&quot; : &quot;It is.a react app&quot; <br>   &quot;dependencies&quot; : { <br>       &quot;react&quot; : &quot;^17.0.2&quot;, <br>       &quot;react-dom&quot; : &quot;^17.0.2&quot;, <br>       &quot;react-icons&quot; : &quot;^4.3.1&quot;, <br>       &quot;react-router&quot; : &quot;^6.2.1&quot;, <br>       &quot;react-router-dom&quot; : &quot;^6.2.1&quot; <br>}, </pre><p>3. To enable routing in a React application, you typically start by configuring the BrowserRouter in the index.js file, which serves as the main entry point of the application. This sets up the routing functionality for the entire application.</p><pre>import {StrictMode } from &quot;react&quot;; <br>import {BrowserRouter} from &quot;react-router-dom&quot; <br>import ReactDOM from &quot;react-router-dom&quot; <br>import App from &quot;./App&quot;<br><br>const root = document.getElementById(&quot;root&quot;) <br>ReactDOM.render( <br>&lt;StrictMode&gt; <br>    &lt;BrowserRouter&gt; <br>      &lt;App /&gt; <br>   &lt;/BrowserRouter&gt; <br>&lt;/StrictMode&gt;, <br>  root<br>);</pre><p>4. Make different files for routing:</p><p>Considering we are making a portfolio website:</p><p>About Us Page:</p><pre>function About() { <br>    return ( <br>       &lt;div&gt; <br>            &lt;h1&gt; This is the about page &lt;/h1&gt; <br>      &lt;/div&gt; <br>    ); <br>} <br>export default About; </pre><p>Home Page:</p><pre>function Home() { <br>    return ( <br>       &lt;div&gt; <br>            &lt;h1&gt; This is the home page &lt;/h1&gt; <br>      &lt;/div&gt; <br>    ); <br>} <br>export default Home; </pre><p>Contact Page:</p><pre>function Contact() { <br>    return ( <br>       &lt;div&gt; <br>            &lt;h1&gt; This is the Contact page &lt;/h1&gt; <br>      &lt;/div&gt; <br>    ); <br>} <br>export default Home; </pre><p>5. In the App.js file, which acts as the central component of your application, you define the routes and specify which components should be rendered based on the URL path. This is where you set up the logic for how your application should behave when different routes are accessed.</p><p>Within App.js, you import the required components from the react-router-dom library, such as Route, Switch, Link, and BrowserRouter. These components provide the building blocks for configuring and managing routing in your application.</p><p>Using the imported components, you define the routes by specifying the URL paths and the corresponding components that should be rendered for each route. This allows you to control the content and functionality of your application based on the user’s navigation.</p><p>By structuring and organizing the routes in App.js, you establish the foundation for navigation and content rendering within your application, ensuring that the correct components are displayed based on the current URL path.</p><pre>import {Routes , Route } from &quot;react-router-dom&quot; <br>import Home from &quot;./components/Home/Home&quot; <br>import Contact from &quot;./components/Contact/Contact&quot;<br>import About from &quot;./components/About/About&quot; <br>const App = () =&gt; { <br>   return ( <br>      &lt;div className=&quot;App&quot;&gt; <br>        &lt;Routes&gt; <br>            &lt;Route path=&quot;/&quot; component={&lt;Home/&gt; } /&gt; <br>            &lt;Route path=&quot;/about&quot; component={&lt;About/&gt; } /&gt; <br>            &lt;Route path=&quot;/contact&quot; component={&lt;Contact/&gt; } /&gt;<br>       &lt;/Routes&gt; <br>    &lt;/div&gt; <br>)} <br>export default App</pre><p><em>This is how we install and set up the basic boilerplate using React Router. After that, it can be extended with its components navigating with respect to website requirements… Hey, you reached more than half, continue reading….</em></p><p>Now let&#39;s understand Switch, Link, and NavLink components from the react-router-dom library:</p><pre>import React from &#39;react&#39;;<br>import { BrowserRouter as Router, Route, Switch, Link, NavLink } from &#39;react-router-dom&#39;;<br><br>// Home component<br>const Home = () =&gt; &lt;h1&gt;Home Page&lt;/h1&gt;;<br><br>// About component<br>const About = () =&gt; &lt;h1&gt;About Page&lt;/h1&gt;;<br><br>// Contact component<br>const Contact = () =&gt; &lt;h1&gt;Contact Page&lt;/h1&gt;;<br><br>// App component<br>const App = () =&gt; {<br>  return (<br>    &lt;Router&gt;<br>      &lt;nav&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;<br>            &lt;NavLink exact to=&quot;/&quot; activeClassName=&quot;active&quot;&gt;Home&lt;/NavLink&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;NavLink to=&quot;/about&quot; activeClassName=&quot;active&quot;&gt;About&lt;/NavLink&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;NavLink to=&quot;/contact&quot; activeClassName=&quot;active&quot;&gt;Contact&lt;/NavLink&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/nav&gt;<br><br>      &lt;Switch&gt;<br>        &lt;Route exact path=&quot;/&quot; component={Home} /&gt;<br>        &lt;Route path=&quot;/about&quot; component={About} /&gt;<br>        &lt;Route path=&quot;/contact&quot; component={Contact} /&gt;<br>      &lt;/Switch&gt;<br>    &lt;/Router&gt;<br>  );<br>};<br><br>export default App;</pre><p>In the above code:</p><ul><li>The Router component wraps the entire application and provides the routing functionality.</li><li>The nav element contains the navigation menu with Link or NavLink components for each route.</li><li>Link and NavLink components are used to create links for navigating between different routes. The exact prop is used for exact path matching, and the activeClassName prop adds a CSS class to the active link.</li><li>The Switch component ensures that only the first matching Route is rendered.</li><li>Route components define the paths and the components to be rendered for each route.</li></ul><p>With this setup, when a user clicks on a navigation link, the corresponding component will be rendered in the application based on the URL path. For example, accessing “/about” will render the About component.</p><p><strong>Here is the overview of all these components:</strong></p><ol><li>Routes: Routes refer to the collection of different URL paths defined in a web application. They define the available destinations or pages that users can navigate to. Routes typically map to specific components or views in the application.</li><li>Route: A Route component is used to define a specific route within the application. It specifies the URL path and the component to be rendered when that route is matched. Route components are typically used in routing libraries/frameworks like React Router.</li><li>Browser Route: A Browser Route is a type of routing mechanism that leverages the browser’s built-in history API. It allows the application to handle navigation and rendering of different components based on the URL path. Browser routing uses JavaScript to manipulate the browser’s history and handle navigation without making requests to the server for every page change.</li><li>NavLink: NavLink is a component typically provided by routing libraries like React Router. It is used to create navigation links within the application. NavLink is similar to the HTML anchor tag (&lt;a&gt;) but provides additional functionality specific to routing. It adds an &quot;active&quot; class to the link when it matches the current URL, allowing for visual highlighting of the active route.</li><li>Link: Link is another component typically provided by routing libraries like React Router. It is used to create links within the application for navigating between different routes. Link components ensure that the page does not reload entirely when a link is clicked. Instead, they use JavaScript to update the URL and render the appropriate component without making a full page refresh.</li></ol><h3><strong>FAQs:</strong></h3><blockquote>Does NavLink redirect to a new page ?</blockquote><p>No, the NavLink component does not redirect to a new page in the traditional sense. Instead, it handles navigation within a Single Page Application (SPA) by updating the URL and rendering the appropriate component without causing a full page refresh.</p><p>When a NavLink is clicked, it uses JavaScript to update the URL in the browser&#39;s address bar based on the specified to prop. This triggers the routing mechanism to match the new URL path with the defined routes and render the corresponding component for that route.</p><p>The key difference is that the navigation happens within the same page without a complete reload of the entire HTML document. This is the behavior commonly seen in SPAs, where the application loads once, and subsequent navigation occurs within the same page, resulting in a faster and more seamless user experience.</p><blockquote>Of the mentioned above routing techniques, which renders a new page and which not ??</blockquote><p>NavLink and Link components are used for in-app navigation and can update the URL without causing a full page reload. The Route component handles rendering within the existing page based on the current URL and route matches, without triggering a new page.</p><blockquote>What is the difference between a router and a switch?</blockquote><p>The switch works just as the switch statement, by going through each and every route but once it matches the current URL with the route path, it returns back from there rendering that route component specifically. But Router is a standard library under which the switch is a component that helps users to navigate via the implementation of routing in web applications.</p><blockquote>Which Router is best for React JS?</blockquote><p>BrowserRouter is commonly used for developing small-scale web applications and learning projects. However, it may not be the most suitable option for production-level applications due to its limitations. One drawback is that it is not compatible with legacy servers, resulting in a “Cannot GET Route” error. Additionally, server configuration is required to handle every route defined on the client side, adding complexity and maintenance overhead. Another limitation is that BrowserRouter is primarily designed for Single-Page Applications (SPAs), limiting its functionality to more complex multi-page applications.</p><p>For production-level applications, other routing solutions like HashRouter or StaticRouter are often preferred. HashRouter uses the hash portion of the URL to manage routing, making it compatible with legacy servers and eliminating the need for server configuration. StaticRouter is useful for server-side rendering (SSR) applications and handles routing on the server side, providing better compatibility and performance.</p><p>It’s important to choose the appropriate routing solution based on the specific requirements and constraints of your project, considering factors such as server compatibility, routing complexity, and scalability.</p><p>That&#39;s the wrap. Hope you understood routing in React. Web development is the heart of routing!</p><p>Connect with me on Twitter or LinkedIn — — — -&gt;</p><blockquote><a href="https://www.linkedin.com/in/nirbhay-kumar-a826531ba/">https://www.linkedin.com/in/nirbhay-kumar-a826531ba/</a></blockquote><blockquote><a href="https://twitter.com/Nickky_729">https://twitter.com/Nickky_729</a></blockquote><h3>Build Apps with reusable components, just like Lego</h3><p><a href="https://bit.cloud/"><strong>Bit</strong></a><strong>’s open-source tool </strong>help 250,000+ devs to build apps with components.</p><p>Turn any UI, feature, or page into a <strong>reusable component</strong> — and share it across your applications. It’s easier to collaborate and build faster.</p><p><strong>→ </strong><a href="https://bit.dev/"><strong>Learn more</strong></a></p><p>Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:</p><h3>→ <a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">Micro-Frontends</a></h3><h3>→ <a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">Design System</a></h3><h3>→ <a href="https://bit.cloud/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4">Code-Sharing and reuse</a></h3><h3>→ <a href="https://www.youtube.com/watch?v=5wxyDLXRho4&amp;t=2041s">Monorepo</a></h3><h3>Learn more:</h3><ul><li><a href="https://blog.bitsrc.io/creating-a-developer-website-with-bit-components-3f4083a7f050">Creating a Developer Website with Bit components</a></li><li><a href="https://blog.bitsrc.io/how-we-build-micro-front-ends-d3eeeac0acfc">How We Build Micro Frontends</a></li><li><a href="https://blog.bitsrc.io/how-we-build-our-design-system-15713a1f1833">How we Build a Component Design System</a></li><li><a href="https://bit.dev/blog/how-to-reuse-react-components-across-your-projects-l4pz83f4/">How to reuse React components across your projects</a></li><li><a href="https://blog.bitsrc.io/5-ways-to-build-a-react-monorepo-a294b6c5b0ac">5 Ways to Build a React Monorepo</a></li><li><a href="https://bit.dev/blog/how-to-create-a-composable-react-app-with-bit-l7ejpfhc/">How to Create a Composable React App with Bit</a></li><li><a href="https://itnext.io/how-to-reuse-and-share-react-components-in-2023-a-step-by-step-guide-85642e543afa">How to Reuse and Share React Components in 2023: A Step-by-Step Guide</a></li><li><a href="https://blog.bitsrc.io/5-tools-for-building-react-component-libraries-in-2023-d8fb8e4c13b4">5 Tools for Building React Component Libraries in 2023</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=488344ea4a8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/routing-magic-in-react-building-dynamic-web-applications-488344ea4a8a">Routing Magic in React: Building Dynamic Web Applications</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Asynchronous JavaScript: Unleashing the Power of Non-Blocking Code !]]></title>
            <link>https://nirbhaykumar5572.medium.com/the-art-of-asynchronous-javascript-unleashing-the-power-of-non-blocking-code-f38782646df4?source=rss-da124e7601a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38782646df4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[web-dev-101]]></category>
            <dc:creator><![CDATA[Nirbhay kumar]]></dc:creator>
            <pubDate>Fri, 19 May 2023 11:52:08 GMT</pubDate>
            <atom:updated>2023-05-19T11:53:37.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Art of Asynchronous JavaScript: Unleashing the Power of Non-Blocking Code !</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNV3df-o_cVjQIKah9zpdQ.jpeg" /></figure><p>Welcome to the exciting world of asynchronous JavaScript! In the realm of web development, where responsiveness and user experience are paramount, understanding and harnessing the power of asynchronous programming is essential. Asynchronous JavaScript, often referred to as async JavaScript, enables us to execute code without blocking the main thread, ensuring smooth and efficient operations.</p><p>In this blog, we will dive deep into the concepts and techniques of async JavaScript. We will explore how asynchronous programming enhances the performance and responsiveness of web applications by allowing multiple tasks to run concurrently. Whether you are a beginner looking to grasp the fundamentals or an experienced developer seeking advanced strategies, this guide will equip you with the knowledge and tools to make your JavaScript code more efficient, scalable, and user-friendly.</p><p>We will unravel the mysteries of async JavaScript, demystify concepts like callbacks, promises, and async/await, and uncover practical use cases and best practices. The blog is going to be a bit long, kindly hang tight , you will enjoy it ✌️!</p><ol><li><strong>Promises</strong></li></ol><p>A promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Essentially, it’s a returned object to which you attach callbacks, as opposed to passing callbacks into a function.</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    <br>   let flag = false;<br>   let n = 7;<br>   for(let i = 1; i &lt;= 7; i++)<br>      if(n % i === 0) <br>          flag = true;<br>        <br>    // if no is is prime<br><br>    // After 1 second, check the condition and resolve or reject the promise<br>    setTimeout(() =&gt; {<br>        if (flag) {<br>            resolve(&#39;Promise fulfilled!&#39;);<br>        } else {<br>            reject(&#39;Promise rejected!&#39;);<br>        }<br>    }, 1000);<br>});<br><br>// Attach then() and catch() handlers to the Promise<br>promise<br>    .then(value =&gt; {<br>        // This will be executed if the promise is resolved<br>        console.log(value); // Output: Promise fulfilled!<br>    })<br>    .catch(error =&gt; {<br>        // This will be executed if the promise is rejected<br>        console.log(error);<br>    });</pre><p><em>In this example, a promise is created and will either resolve or reject after 1 second, depending on the value of condition. The </em><em>resolve function is called if the promise is successful, and reject is called if the promise fails.</em></p><p><em>The </em><em>then method is called when the promise is resolved and receives the value passed to the resolve function. Similarly, the catch method is called when the promise is rejected and receives the value passed to the reject function.</em></p><p><strong>2. setTimeout</strong></p><p>The setTimeout function plays a key role in this problem. It&#39;s a method that calls a function or evaluates an expression after a specified number of milliseconds. In JavaScript, setTimeout is used to delay the execution of a piece of code.</p><pre>console.log(&quot;Starting the timer...&quot;);<br><br>setTimeout(() =&gt; {<br>    console.log(&quot;Timeout completed!&quot;);<br>}, 2000);</pre><p><em>In our example, the callback function is a simple arrow function that logs “Timeout completed!” to the console. We set the delay to 2000 milliseconds, equivalent to 2 seconds. However, it’s important to note that the JavaScript runtime does not wait for this delay before moving on to the next line of code. Instead, it continues executing subsequent instructions without pausing, showcasing the non-blocking characteristic of JavaScript.</em></p><p><em>Once the specified delay has passed (in this case, 2 seconds), the callback function is added to the task queue. However, it’s crucial to understand that the execution of the callback function might not occur immediately after the delay. Due to the event-driven nature of JavaScript and the single-threaded event loop, the actual execution might experience a slight delay. This delay is caused by the runtime’s handling of other tasks that are queued ahead of the callback function.</em></p><p>Consider a situation where the main JavaScript thread is occupied with a lengthy operation. In such cases, even if the timer has completed its background task, the callback function would still have to wait for the blocking operation to finish. The event loop can only process one task at a time and handles tasks in the order they are queued.</p><p>Therefore, it’s important to interpret the “2 seconds” specified in setTimeout as the minimum delay before the callback function is invoked, rather than a guaranteed delay. If the JavaScript runtime is engaged with other tasks, it might take longer than 2 seconds for the callback function to be executed. This behavior emphasizes the significance of comprehending the asynchronous nature of JavaScript, as it can significantly impact your code’s performance and behavior.</p><p>Additionally, JavaScript provides a useful function called clearTimeout, which can cancel a timeout previously established using setTimeout. clearTimeout is handy when you want to prevent the execution of a callback function before it occurs naturally.</p><pre>console.log(&quot;lets start&quot;);<br>// setTimeout returns a Timeout object which can be used to reference the timer<br>let timeoutId = setTimeout(() =&gt; {<br>  console.log(&quot;Timeout completed!&quot;);<br>}, 2000);<br><br>// Some condition or logic<br>if (/* some condition */) {<br>// Cancels the timeout<br>  clearTimeout(timeoutId);<br>}</pre><p>To summarize, this example highlights the non-blocking behavior of JavaScript and how setTimeout, along with the event loop, allows for asynchronous execution. Understanding and effectively utilizing asynchronous programming in JavaScript can greatly enhance the responsiveness and efficiency of your code.</p><p><em>Yoooo, the article is getting long, but what can we do considering nature of javascript…………….a bit more patience, hand tight for a while😊….</em></p><p><strong>3. JavaScript’s Event Loop</strong></p><p>The Event Loop acts as a supervisor, ensuring that JavaScript can efficiently handle asynchronous tasks. It keeps track of both the call stack and the task queue. Whenever the call stack is free, it grabs the next task from the task queue and executes it. This process allows JavaScript to seamlessly handle asynchronous operations without blocking the main thread.</p><p>4. <strong>Asynchronous Callbacks</strong></p><p>JavaScript handles concurrent operations by utilizing asynchronous code execution.</p><ol><li>When an async operation is encountered, such as setTimeout or fetch, JavaScript sets it up and continues executing the rest of the code without waiting for the operation to complete.</li><li>The async operation runs in the background, separate from the main JavaScript thread. Once the async operation finishes, its callback function is placed in the task queue.</li><li>The Event Loop continuously checks if the call stack is empty. When it is, the Event Loop takes the first task from the task queue and pushes it onto the call stack for immediate execution.</li><li>This process repeats, allowing JavaScript to handle multiple operations concurrently despite being single-threaded.</li></ol><p>To introduce delays in code execution, a “sleep” function can be created using promises and setTimeout. This function returns a promise that resolves after a specified delay, simulating the delay in code execution.</p><p>JavaScript offers the async and await keywords to simplify working with promises. By declaring a function as async, it returns a promise when called. The async function can use await to pause execution until a promise is fulfilled, making the asynchronous code look and behave more like synchronous code.</p><p>In a web page scenario where data needs to be loaded from a server upon button click, it’s crucial to handle the request asynchronously to avoid freezing the entire page. Instead of waiting for the server’s response, the goal is to allow the page to remain responsive. This can be achieved using asynchronous techniques like this…</p><pre>// The &#39;async&#39; keyword allows the use of &#39;await&#39; inside the function<br>button.addEventListener(&#39;click&#39;, async () =&gt; {<br>    // Show a loading spinner<br>    preloader.style.display = &#39;block&#39;;<br><br>    try {<br>        // Fetch data from server<br>        let response = await fetch(&#39;https://api.icons/preloader&#39;);<br>        // Parse the JSON response<br>        let items = await response.json();<br>        // Update the UI with the new items<br>        displayItems(items);<br>    } catch (error) {<br>        // Handle any errors<br>        console.error(&#39;Error:&#39;, error);<br>    } finally {<br>        // Hide the loading spinner<br>        preloader.style.display = &#39;none&#39;;<br>    }<br>});</pre><p><strong>5. Async/await</strong></p><p>Async/await simplifies writing and understanding asynchronous code by providing a more straightforward syntax. It allows us to pause code execution until promises are resolved, eliminating the need for lengthy .then() and .catch() chains. This makes the code more readable and helps handle errors more concisely.</p><pre>// Using explicit .then() and .catch() with promises<br>fetchData()<br>  .then(res =&gt; {<br>    // Handle the response<br>    return processData(res);<br>  })<br>  .then(ress =&gt; {<br>    // Handle the processed data<br>  })<br>  .catch(err =&gt; {<br>    // Handle any errors<br>  });<br><br>//more readable code <br>// Using async/await<br>async function nirbhayKumar() {<br>  try {<br>    const response = await fetchData();<br>    console.log(&quot;Response:&quot;, response);<br><br>    const result = await processData(response);<br>    console.log(&quot;Processed data:&quot;, result);<br>  } catch (error) {<br>    console.error(&quot;Error:&quot;, error);<br>  }<br>}<br><br>nirbhayKumar();</pre><p>In the first approach, promises are chained together using .then() to handle the response and process the data sequentially. If any errors occur, they are caught and handled in the .catch() block.</p><p>The second approach utilizes the async/await syntax, making the code appear more synchronous and easier to follow. Inside an async function, the await keyword is used to pause the execution until promises are resolved. This allows for a linear flow of code execution, similar to traditional synchronous programming. Any errors that arise are caught and handled in the try-catch block.</p><h4>6. Promise Chaining</h4><p>Promise chaining is a technique in JavaScript for executing multiple asynchronous operations in a sequence. It helps avoid nested callbacks and improves code readability. Each then in the chain receives the result of the previous promise, enabling easy data flow between steps. If a promise in the chain is rejected, subsequent then methods are skipped until a catch method is encountered.</p><pre>fetchData()<br>  .then(responseData =&gt; {<br>    console.log(&quot;Response:&quot;, responseData);<br>    return processData(responseData);  // This returns a new promise<br>  })<br>  .then(processedData =&gt; {<br>    console.log(&quot;Processed data:&quot;, processedData);<br>    return furtherProcessing(processedData);  // This returns another new promise<br>  })<br>  .then(finalResult =&gt; {<br>    console.log(&quot;Final result:&quot;, finalResult);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&quot;Error:&quot;, error);<br>  });</pre><p>fetchData, processData, and furtherProcessing are all asynchronous functions that return promises. The then methods are chained together, with each one waiting for the previous promise to resolve before starting its operation. If any promise in the chain is rejected, the catch method at the end will be invoked to handle the error.</p><p>7<strong>. Importance of finally</strong></p><p>In JavaScript, the .finally method is a powerful feature of Promises. It allows you to specify code that will be executed regardless of whether the promise is fulfilled or rejected. This makes it useful for cleanup operations or tasks that should always be performed, irrespective of the promise&#39;s outcome.</p><pre>let onload = true;<br><br>fetch(&#39;https://api/github/user/nirbhay97&#39;)<br>  .then(res =&gt; {<br>    if (!res.ok) {<br>      throw new Error(&#39;Network response was not ok&#39;);<br>    }<br>    return response.json();<br>  })<br>  .then(data =&gt; console.log(data.public_repos))<br>  .catch(error =&gt; console.error(&#39;Error:&#39;, error))<br>  .finally(() =&gt; {<br>    onload = false;<br>    console.log(&#39;Fetch operation finished&#39;);<br>  });</pre><p>We’re using fetch here (which returns a promise) to retrieve count of public repos (nirbhay97) username has on github with api. We then use .then to handle the response, and .catch to handle any errors. Finally, regardless of whether the fetch operation was successful or not, .finally is called to set isload to false and log a message to the console.</p><blockquote>Yayyyy, you finally unleashed the power of asynch js, i am sure, this will help you in optimzation of your application, come again to read more blogs, i <strong>promise</strong>, you wont have to<strong> await. Give a thumbs up if you liked. Bye👋👋</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38782646df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>