<?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 Royal Jain on Medium]]></title>
        <description><![CDATA[Stories by Royal Jain on Medium]]></description>
        <link>https://medium.com/@royaljain0203?source=rss-cfecf0654b7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zlCMj_Kp3PZZsaf9DoWQbw.jpeg</url>
            <title>Stories by Royal Jain on Medium</title>
            <link>https://medium.com/@royaljain0203?source=rss-cfecf0654b7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:16:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@royaljain0203/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[React i18next: Easily Add Translations to Your Apps]]></title>
            <link>https://medium.com/codeparrot-ai/react-i18next-easily-add-translations-to-your-apps-5a5047ccf59a?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5047ccf59a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[i18next]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 14:25:48 GMT</pubDate>
            <atom:updated>2024-07-01T14:25:48.198Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to add translations to your React apps using i18next and enjoy a seamless multilingual experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD8wb3xLa_ew9acyT2zQKw.png" /></figure><p>Multilingual support is a crucial aspect of modern web applications. By providing translations in multiple languages, you can cater to a diverse audience and enhance user experience. React applications can benefit significantly from internationalization libraries like i18next, which simplify the process of adding translations to your app.</p><p>This also means that you can easily switch between languages without reloading the page, making your app more user-friendly and accessible. In this article, we’ll explore how to add translations to your React applications using i18next and create a seamless multilingual experience for your users.</p><h3>What is i18next?</h3><p><a href="https://www.i18next.com/">i18next</a> is a popular internationalization library for JavaScript applications. It provides a robust framework for managing translations, formatting dates, numbers, and handling pluralization. i18next supports multiple backends for storing translations, making it versatile and adaptable to various project requirements.</p><h3>Getting Started with i18next in React</h3><p>Let’s get started by creating a new React application using Vite, a modern build tool that offers fast development and optimized production builds.</p><pre>npm create vite@latest</pre><p>Next, enter the project directory and install the necessary dependencies:</p><pre>npm install<br>npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector</pre><p>The i18next package is the core library, while react-i18next provides React bindings for i18next. The i18next-http-backend package allows loading translations from a remote server, and i18next-browser-languagedetector detects the user&#39;s preferred language based on the browser settings.</p><p>To start out, here’s my App.jsx file:</p><pre>import &#39;./App.css&#39;;</pre><pre>function App() {<br>  return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;header className=&quot;app-header&quot;&gt;<br>        &lt;h1&gt;Welcome to My Multilingual App&lt;/h1&gt;<br>        &lt;p&gt;Learn how to add translations to your React app easily and efficiently.&lt;/p&gt;<br>      &lt;/header&gt;<br>      &lt;main className=&quot;app-main&quot;&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;About This Tutorial&lt;/h2&gt;<br>          &lt;p&gt;<br>            This tutorial will guide you through the steps needed to integrate translations into your React application. <br>            By the end of this tutorial, you will be able to provide a seamless multilingual experience to your users.<br>          &lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;Why Add Translations?&lt;/h2&gt;<br>          &lt;p&gt;<br>            Adding translations to your app allows you to reach a broader audience. In today&#39;s globalized world, <br>            it&#39;s crucial to make your content accessible to users who speak different languages.<br>          &lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;Getting Started&lt;/h2&gt;<br>          &lt;p&gt;<br>            To get started with translations, we will use a popular library called &lt;strong&gt;react-i18next&lt;/strong&gt;. <br>            This library provides all the tools you need to translate your app&#39;s content.<br>          &lt;/p&gt;<br>        &lt;/section&gt;<br>      &lt;/main&gt;<br>      &lt;footer className=&quot;app-footer&quot;&gt;<br>        &lt;p&gt;&amp;copy; 2024 My Multilingual App. All rights reserved.&lt;/p&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>It just has some placeholder content for now. We’ll add translations to this app shortly.</p><h3>Setting Up i18next</h3><p>To configure i18next in your React application, create a new file called i18n.js in the src directory:</p><pre>import i18next from &quot;i18next&quot;;<br>import { initReactI18next } from &quot;react-i18next&quot;;<br>import LanguageDetector from &quot;i18next-browser-languagedetector&quot;;<br>import HTTPApi from &quot;i18next-http-backend&quot;;</pre><pre>i18next<br>  .use(initReactI18next)<br>  .use(LanguageDetector)<br>  .use(HTTPApi)<br>  .init({<br>    fallbackLng: &quot;en&quot;,<br>    interpolation: {<br>      escapeValue: false,<br>    },<br>  });</pre><pre>export default i18next;</pre><p>In the i18n.js file, we have several key components to set up i18next for our React application:</p><ul><li><strong>Importing i18next and its dependencies:</strong> We start by importing the core i18next library, along with its React bindings, language detector, and HTTP backend.</li><li><strong>Using the React integration:</strong> initReactI18next provides the integration for using i18next with React.</li><li><strong>Using the language detector:</strong> LanguageDetector helps detect the user’s preferred language based on their browser settings.</li><li><strong>Using the HTTP backend:</strong> HTTPApi allows loading translations from a remote server.</li><li><strong>Initializing i18next:</strong> The init function configures i18next with a fallback language (English in this case) and sets interpolation options.</li></ul><p>This setup ensures that i18next is properly configured to handle translations and detect the user’s preferred language.</p><h3>Loading Translations</h3><p>Next, we’ll create translation files for different languages. In the public directory, create a new folder called locales and add subfolders for each language you want to support, such as en for English and fr for French. Inside each language folder, create a translation.json file with the respective translations.</p><p>Here’s an example of the translation.json file for English (public/locales/en/translation.json):</p><pre>{<br>  &quot;welcome_message&quot;: &quot;Welcome to My Multilingual App&quot;,<br>  &quot;tutorial_intro&quot;: &quot;Learn how to add translations to your React app easily and efficiently.&quot;,<br>  &quot;about_this_tutorial&quot;: &quot;About This Tutorial&quot;,<br>  &quot;about_this_tutorial_text&quot;: &quot;This tutorial will guide you through the steps needed to integrate translations into your React application. By the end of this tutorial, you will be able to provide a seamless multilingual experience to your users.&quot;,<br>  &quot;why_add_translations&quot;: &quot;Why Add Translations?&quot;,<br>  &quot;why_add_translations_text&quot;: &quot;Adding translations to your app allows you to reach a broader audience. In today&#39;s globalized world, it&#39;s crucial to make your content accessible to users who speak different languages.&quot;,<br>  &quot;getting_started&quot;: &quot;Getting Started&quot;,<br>  &quot;getting_started_text&quot;: &quot;To get started with translations, we will use a popular library called react-i18next. This library provides all the tools you need to translate your app&#39;s content.&quot;<br>}</pre><p>And for French (public/locales/fr/translation.json):</p><pre>{<br>  &quot;welcome_message&quot;: &quot;Bienvenue dans mon application multilingue&quot;,<br>  &quot;tutorial_intro&quot;: &quot;Apprenez à ajouter des traductions à votre application React facilement et efficacement.&quot;,<br>  &quot;about_this_tutorial&quot;: &quot;À propos de ce tutoriel&quot;,<br>  &quot;about_this_tutorial_text&quot;: &quot;Ce tutoriel vous guidera à travers les étapes nécessaires pour intégrer des traductions dans votre application React. À la fin de ce tutoriel, vous serez en mesure de fournir une expérience multilingue transparente à vos utilisateurs.&quot;,<br>  &quot;why_add_translations&quot;: &quot;Pourquoi ajouter des traductions?&quot;,<br>  &quot;why_add_translations_text&quot;: &quot;Ajouter des traductions à votre application vous permet de toucher un public plus large. Dans le monde globalisé d&#39;aujourd&#39;hui, il est crucial de rendre votre contenu accessible aux utilisateurs qui parlent différentes langues.&quot;,<br>  &quot;getting_started&quot;: &quot;Commencer&quot;,<br>  &quot;getting_started_text&quot;: &quot;Pour commencer avec les traductions, nous allons utiliser une bibliothèque populaire appelée react-i18next. Cette bibliothèque fournit tous les outils nécessaires pour traduire le contenu de votre application.&quot;<br>}</pre><p>These translation files contain key-value pairs for each translation string. We’ll use these translations to display content in different languages based on the user’s preference.</p><h3>Using Translations in Your App</h3><p>Now that we have set up i18next and loaded translations for different languages, let’s integrate them into our React application</p><p>First, make sure to import and initialize i18next at the entry point of your application in main.jsx:</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.jsx&#39;<br>import &#39;./index.css&#39;<br>import &#39;./i18n.js&#39;</pre><pre>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;,<br>)</pre><p>Next, update your App.jsx file to use the useTranslation hook provided by react-i18next:</p><pre>import &#39;./App.css&#39;;<br>import { useTranslation } from &#39;react-i18next&#39;;</pre><pre>function App() {<br>  const { t } = useTranslation();</pre><pre>return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;header className=&quot;app-header&quot;&gt;<br>        &lt;h1&gt;{t(&#39;welcome_message&#39;)}&lt;/h1&gt;<br>        &lt;p&gt;{t(&#39;tutorial_intro&#39;)}&lt;/p&gt;<br>      &lt;/header&gt;<br>      &lt;main className=&quot;app-main&quot;&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;about_this_tutorial&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;about_this_tutorial_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;why_add_translations&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;why_add_translations_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;getting_started&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;getting_started_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>      &lt;/main&gt;<br>      &lt;footer className=&quot;app-footer&quot;&gt;<br>        &lt;p&gt;&amp;copy; 2024 My Multilingual App. All rights reserved.&lt;/p&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>The useTranslation hook provides access to the t function, which we use to translate the content based on the key specified in the translation files. By calling t(&#39;key&#39;), we can retrieve the corresponding translation string for that key.</p><h3>Switching Between Languages</h3><p>To enable users to switch between languages, we can add a language selector to our app. Here’s an example of how you can implement a language switcher using the i18next instance:</p><pre>import &#39;./App.css&#39;;<br>import { useTranslation } from &#39;react-i18next&#39;;</pre><pre>function App() {<br>  const { t, i18n } = useTranslation();</pre><pre> const changeLanguage = (lng) =&gt; {<br>    i18n.changeLanguage(lng);<br>  };</pre><pre>  return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;header className=&quot;app-header&quot;&gt;<br>        &lt;h1&gt;{t(&#39;welcome_message&#39;)}&lt;/h1&gt;<br>        &lt;p&gt;{t(&#39;tutorial_intro&#39;)}&lt;/p&gt;<br>        &lt;div className=&quot;language-selector&quot;&gt;<br>          &lt;button onClick={() =&gt; changeLanguage(&#39;en&#39;)}&gt;English&lt;/button&gt;<br>          &lt;button onClick={() =&gt; changeLanguage(&#39;fr&#39;)}&gt;Français&lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/header&gt;<br>      &lt;main className=&quot;app-main&quot;&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;about_this_tutorial&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;about_this_tutorial_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;why_add_translations&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;why_add_translations_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>        &lt;section className=&quot;content-section&quot;&gt;<br>          &lt;h2&gt;{t(&#39;getting_started&#39;)}&lt;/h2&gt;<br>          &lt;p&gt;{t(&#39;getting_started_text&#39;)}&lt;/p&gt;<br>        &lt;/section&gt;<br>      &lt;/main&gt;<br>      &lt;footer className=&quot;app-footer&quot;&gt;<br>        &lt;p&gt;&amp;copy; 2024 My Multilingual App. All rights reserved.&lt;/p&gt;<br>      &lt;/footer&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>With this implementation, users can switch between English and French by clicking the respective language buttons. The changeLanguage function changes the language based on the selected locale.</p><p>If you’ve followed along, you should now have a React application with multilingual support using i18next. Here is a preview of the app in English and French:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*bg3JlHd_NrzGAoa7" /></figure><h3>Fall Back to Default Language</h3><p>In the event that a translation is missing for a specific key, i18next will fall back to the default language specified in the configuration. This ensures that users always see content, even if translations are missing for a particular language.</p><p>For example, let’s add a button for a language that doesn’t have translations in our app:</p><pre>&lt;div className=&quot;language-selector&quot;&gt;<br>  &lt;button onClick={() =&gt; changeLanguage(&#39;en&#39;)}&gt;English&lt;/button&gt;<br>  &lt;button onClick={() =&gt; changeLanguage(&#39;fr&#39;)}&gt;Français&lt;/button&gt;<br>  &lt;button onClick={() =&gt; changeLanguage(&#39;es&#39;)}&gt;Español&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Since we haven’t provided translations for Spanish, i18next will fall back to the default language (English) when the user selects Spanish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*uJ9EHiRhA_CTxGfW" /></figure><p>By adding translations to your React applications, you can provide a seamless multilingual experience to users around the world. i18next simplifies the process of managing translations and ensures that your app is accessible to a diverse audience.</p><p>I hope this tutorial has been helpful in guiding you through the process of adding translations to your React apps. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5047ccf59a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/react-i18next-easily-add-translations-to-your-apps-5a5047ccf59a">React i18next: Easily Add Translations to Your Apps</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Npm vs Npx: Use case and Differences]]></title>
            <link>https://medium.com/codeparrot-ai/npm-vs-npx-use-case-and-differences-a24f95493e72?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a24f95493e72</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[npx]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 13:30:14 GMT</pubDate>
            <atom:updated>2024-07-01T13:30:14.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqmYMZ9bPUNVbDz088WLpw.jpeg" /><figcaption>npm vs npx</figcaption></figure><p>Developers often get confused between npm and npx, which one to use. In reality, they are different tools which can be used together.</p><h3>npm ➡️ Package Manager</h3><p><strong>npm</strong> is the default package management system for JavaScript, enabling developers to share and consume packages from the npm registry.</p><h4>Definition and Core Functions</h4><p>npm helps manage packages in a project, allowing you to add, update, and remove dependencies. It also facilitates version control and package distribution, making it easier to manage complex projects with numerous dependencies.</p><h4>Key Features</h4><ul><li><strong>Vast Registry</strong>: npm provides access to the largest registry of JavaScript packages, offering a wide range of functionalities and tools for developers.</li><li><strong>Semantic Versioning</strong>: It supports semantic versioning, allowing developers to manage package versions and dependencies effectively.</li><li><strong>Easy-to-use CLI</strong>: npm’s command-line interface (CLI) simplifies package management tasks, such as installing packages, setting up projects, and running scripts defined in package.json.</li></ul><h4>Code Example</h4><p>Creating a new project and installing a package is straightforward with npm. Here’s a basic example:</p><pre>npm init -y  # Initializes a new project<br>npm install express  # Installs the Express.js framework</pre><p>This example demonstrates initializing a new Node.js project and adding Express.js as a dependency.</p><h3>npx ➡️ Package Executer</h3><p><strong>npx</strong> is a package execution tool that comes bundled with npm 5.2.0 and later. It’s designed to improve the experience of using packages from the npm registry by allowing developers to run commands without installing them globally.</p><h4>Definition and Purpose</h4><p>npx enables the execution of npm package binaries with ease. It’s particularly useful for running packages that are used occasionally or for testing different versions of a package without affecting the global installation.</p><h4>Key Advantages</h4><ul><li><strong>No Global Installation Required</strong>: Run CLI tools and other executables without cluttering your global namespace.</li><li><strong>Direct Execution from npm Registry</strong>: Easily execute any version of a package directly from the npm registry without having to install it first.</li><li><strong>Simplifies One-off Commands</strong>: Ideal for running tasks like creating new projects with boilerplate generators.</li><li><strong>Run from Github</strong>: Execute codes from GitHub repositories or gists seamlessly with npx. 📁</li></ul><h4>Steps to Execute a Gist Script with npx:</h4><ol><li><strong>Create a GitHub Gist</strong>: Include your main JavaScript file and a package.json file. The package.json should specify any dependencies your script requires.</li><li><strong>Run the Script</strong>: Use npx followed by the URL of the gist to execute the script directly in your terminal. For example:</li></ol><pre>npx gist.github.com/&lt;username&gt;/&lt;gist_id&gt;</pre><p>Replace &lt;username&gt; with your GitHub username and &lt;gist_id&gt; with the ID of your gist.</p><h4>Code Example</h4><p>Using npx to run a package is simple. For instance, creating a new React app without needing to install Create React App globally:</p><pre>npx create-react-app my-app</pre><p>This command uses npx to execute create-react-app directly, bypassing the need for a global installation.</p><h3>Comparative Analysis 🧐</h3><h4>Installation and Execution</h4><ul><li><strong>npm</strong> is primarily focused on package management-installing, updating, and managing project dependencies. It requires global installation for packages that provide CLI tools intended for direct execution.</li><li><strong>npx</strong>, on the other hand, excels at executing npm packages directly from the npm registry without the need for global installation. This is particularly useful for running tools or scripts as one-off commands without permanently installing them.</li></ul><h4>Use Cases</h4><ul><li><strong>npm</strong> is suited for managing dependencies within a project. It’s the go-to tool for installing libraries and frameworks, ensuring that your project’s dependencies are accurately tracked and maintained.</li><li><strong>npx</strong> shines when you need to run a package, script, or command that you don’t necessarily want to keep installed. It’s ideal for testing out packages, executing build scripts, or running CLI tools.</li></ul><h4>Code Examples</h4><p>For installing and managing dependencies, npm is used:</p><pre>npm install lodash  # Adds lodash as a project dependency</pre><p>For executing a command without installing it globally, npx is used:</p><pre>npx eslint --init  # Runs eslint setup without needing a global install</pre><h3>Practical Application in Projects</h3><p>npm is essential for managing project dependencies, while npx provides flexibility in running tools and scripts, enhancing the development workflow.</p><h4>Integrating with Frontend Development</h4><p>When working with frameworks like React, npm is used to manage the project’s dependencies, while npx can be utilized to start new projects using create-react-app without requiring global installations. This separation of concerns simplifies project setups and tool usage.</p><h4>Optimizing Development Processes</h4><p>Developers can leverage npx to run build tools, test runners, and other utilities directly, streamlining the development process. For example, using npx to run a local development server or to compile Sass/LESS files on the fly enhances productivity.</p><h4>Code Example</h4><p>In package.json, scripts can be defined to automate common tasks using npm and npx:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;npx webpack --config webpack.config.js&quot;<br>  }<br>}</pre><p>This setup demonstrates using npm to run predefined scripts and npx to execute a build process with webpack, illustrating the synergy between npm and npx in a frontend project.</p><h3>Practical Tips:</h3><ul><li><strong>Version Conflicts</strong>: Use npx to test different versions of a package without affecting your global or project-specific installations. This can help in identifying the right version that works with your project before making a permanent addition. 🔍</li><li><strong>Cleaning the Cache</strong>: Over time, the npm cache can grow, potentially causing slow downs or issues. Running npm cache verify or npm cache clean --force can help maintain optimal performance. 🧹</li><li><strong>Speeding Up Installations</strong>: Utilize npm ci instead of npm install when installing dependencies in a CI/CD environment. This command is faster and more reliable as it installs directly from package-lock.json. ⚡</li><li><strong>Securing Your Project</strong>: Regularly run npm audit to identify and fix security vulnerabilities within your project&#39;s dependencies. This command provides a detailed report and remediation guidance. 🔒</li><li><strong>Using npx for CLI Tools</strong>: For tools that you use occasionally, such as create-react-app or eslint, prefer using npx to execute them directly from the registry. This approach keeps your global namespace clean and ensures you&#39;re always using the latest version. 🛠️</li><li><strong>Global vs. Local</strong>: Understand when to install packages globally versus locally. Global installations should be reserved for tools you use across multiple projects, while local installations should be used for project-specific dependencies to ensure consistency and avoid version conflicts.🌍 vs 📦</li></ul><h3>Conclusion</h3><p>Understanding the differences and complementary nature of npm and npx is fundamental for developers. While npm provides a robust framework for managing project dependencies, npx offers the flexibility to execute packages and scripts efficiently. npx helps us avoid versioning, dependency issues and installing unnecessary packages that we just want to try out.</p><h3>Further Learning Resources 📚</h3><p>To dive deeper into npm and npx, explore the following resources:</p><ul><li><a href="https://docs.npmjs.com/">npm Documentation</a></li><li><a href="https://docs.npmjs.com/cli/v7/commands/npx">npx Guide on npm Documentation</a></li></ul><p><em>Originally published at </em><a href="https://codeparrot.ai/blogs/npm-vs-npx">https://codeparrot.ai/blogs/npm-vs-npx</a> <em>on February 3, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a24f95493e72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/npm-vs-npx-use-case-and-differences-a24f95493e72">Npm vs Npx: Use case and Differences</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Three.js for 3D Web Development]]></title>
            <link>https://medium.com/codeparrot-ai/exploring-three-js-for-3d-web-development-c803098d3217?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c803098d3217</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Tue, 07 May 2024 09:06:17 GMT</pubDate>
            <atom:updated>2024-05-07T09:06:17.452Z</atom:updated>
            <content:encoded><![CDATA[<h4>Three.js is a popular JavaScript library for creating 3D graphics on the web. It makes it easy to build interactive 3D applications, games, and visualizations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJhBbN84-WdRWrcY95hEDQ.png" /></figure><p>At its core, Three.js provides a structured approach to 3D scene construction, encompassing everything from the creation of geometric shapes to the manipulation of cameras, lighting, and materials. It includes:</p><ul><li>Scenes: The spatial containers for 3D objects.</li><li>Cameras: The viewpoints through which scenes are rendered.</li><li>Renderers: The engines that draw the 3D visuals onto the screen.</li><li>Geometry: The mathematical models defining the shape of objects.</li><li>Materials: The visual properties of objects, such as color and texture.</li><li>Lights: The elements that simulate illumination within the scene.</li></ul><h3>Why Three.js?</h3><p>Choosing Three.js for 3D web development comes down to several pragmatic considerations. Here are some key reasons why developers opt for Three.js:</p><ul><li>Simplification of 3D Graphics Programming: Three.js abstracts the intricacies of WebGL, allowing developers to create complex 3D visualizations without becoming experts in 3D graphics programming.</li><li>Cross-browser Compatibility: It handles the variability across web browsers and devices, ensuring consistent behavior and performance of 3D content.</li><li>Optimized Performance: The library is designed with performance in mind, enabling the efficient rendering of sophisticated 3D scenes.</li><li>Comprehensive Features: Three.js offers a wide range of features from basic to advanced 3D graphics techniques, allowing for the creation of rich interactive experiences.</li></ul><h3>Setting Up Your First Three.js Scene</h3><p>Creating a basic 3D scene with Three.js involves a few simple steps. Here’s what you need:</p><p>Prerequisites:</p><ul><li>Basic understanding of React.js.</li><li>A modern web browser that supports WebGL.</li></ul><h4>Setting Up the Environment</h4><p>Let’s start by creating a new vite app. You can use the following command to create a new React app with vite:</p><pre>npx create-vite-app my-threejs-app --template react</pre><p>To get started with Three.js, you’ll need to include the library in your project. You can install three.js using the following command:</p><pre>npm install --save three</pre><h3>Creating a Scene</h3><p>A scene in Three.js is like a container that holds all your 3D objects, lights, and cameras. To create a new scene, you can use the following code snippet in src/components/Model.js:</p><pre>import React, { useRef, useEffect } from &quot;react&quot;;<br>import * as THREE from &quot;three&quot;;<br><br>const Model = () =&gt; {<br>  const mountRef = useRef(null);<br>  useEffect(() =&gt; {<br>    const scene = new THREE.Scene();<br>    const camera = new THREE.PerspectiveCamera(<br>      75,<br>      window.innerWidth / window.innerHeight,<br>      0.1,<br>      1000<br>    );<br>    const renderer = new THREE.WebGLRenderer();<br>    renderer.setSize(window.innerWidth, window.innerHeight);<br>    mountRef.current.appendChild(renderer.domElement);<br>    return () =&gt; mountRef.current.removeChild(renderer.domElement);<br>  }, []);<br>  return &lt;div ref={mountRef} /&gt;;<br>};<br>export default Model;</pre><p>The Model component creates a new Three.js scene with a camera and a renderer. It then mounts the renderer to a React ref using the useEffect hook. You can now import and use this component in your React app to display a basic 3D scene.</p><p>Here the PerspectiveCamera is used to define the field of view, aspect ratio, near and far clipping planes. The WebGLRenderer is used to render the scene to the DOM.</p><p>After following these steps you should have a basic Three.js scene set up in your React app. You can now start adding 3D objects, lights, and materials to create more complex scenes and animations.</p><p>To add an animated cube to your component, you can use the following code snippet:</p><pre>const geometry = new THREE.BoxGeometry(1, 1, 1);<br>const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });<br>const cube = new THREE.Mesh(geometry, material);<br><br>jscene.add(cube);<br>camera.position.z = 5;<br><br>const animate = function () {<br>  requestAnimationFrame(animate);<br>  cube.rotation.x += 0.01;<br>  cube.rotation.y += 0.01;<br>  renderer.render(scene, camera);<br>};<br>animate();</pre><p>What this does is, it creates a new BoxGeometry and MeshBasicMaterial for the cube, adds the cube to the scene, and then animates the cube by rotating it on the x and y axes. The requestAnimationFrame function is used to create a loop that updates the cube&#39;s rotation and renders the scene on each frame.</p><p>You can play around with the camera position, cube size, material properties, and animation speed to create different effects and styles in your 3D scene.</p><p>If you’re following along you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sCkK5c3aJvkRnDxa" /></figure><h3>Drawing lines</h3><p>In Three.js, you can draw lines by creating a BufferGeometry and a LineBasicMaterial. Here&#39;s an example of how you can draw a simple line in your scene. You can add the following to src/components/Line.js:</p><pre>const scene = new THREE.Scene();<br><br>const material = new THREE.LineBasicMaterial({ color: &quot;white&quot; });<br>const points = [];<br>points.push(new THREE.Vector3(-10, 0, 0));<br>points.push(new THREE.Vector3(0, 10, 0));<br>points.push(new THREE.Vector3(10, 0, 0));<br>const geometry = new THREE.BufferGeometry().setFromPoints(points);<br>const line = new THREE.Line(geometry, material);<br>scene.add(line);<br>renderer.render(scene, camera);</pre><p>You should see an arrow-like shape drawn in your scene:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*-XgtpFKfZ392Yf07" /></figure><h3>Adding Textures and Materials</h3><p>Three.js provides a wide range of materials and textures that you can use to style your 3D objects. Here’s an example of how you can add a texture to a cube in your scene:</p><pre>import textureUrl from &quot;./texture.jpg&quot;;<br>const texture = new THREE.TextureLoader().load(textureUrl);<br>const material = new THREE.MeshBasicMaterial({ map: texture });</pre><h3>Interactivity</h3><p>Adding basic interactivity, such as rotating an object with mouse movements, can greatly enhance the user experience. This involves listening to mouse events and updating the object’s rotation accordingly. You can do this by event listeners and updating the object’s rotation based on the mouse movement.</p><pre>const onDocumentMouseMove = (event) =&gt; {<br>  event.preventDefault();<br>  const mouseX = (event.clientX / window.innerWidth) * 2 - 1;<br>  const mouseY = -(event.clientY / window.innerHeight) * 2 + 1;<br><br>  cube.rotation.x = mouseY * Math.PI;<br>  cube.rotation.y = mouseX * Math.PI;<br>  renderer.render(scene, camera);<br>};<br><br>document.addEventListener(&quot;mousemove&quot;, onDocumentMouseMove, false);</pre><p>The onDocumentMouseMove function listens for mouse movements and updates the cube&#39;s rotation based on the mouse position. This creates an interactive effect where the cube rotates in response to the mouse movement.</p><p>You should see the cube rotating based on your mouse movements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fvCwj3LyYQymboNl" /></figure><h3>Expanding Your Three.js Skills</h3><p>Once you’ve mastered the basics, you can start experimenting with more complex shapes, adding textures and materials, and introducing interactivity. Three.js provides a wide range of geometries, materials, and APIs to interact with 3D objects, lights, shadows, and much more.</p><h3>Conclusion</h3><p>Three.js opens up a world of possibilities for 3D web development, allowing you to create immersive, interactive experiences with relative ease. While this guide covers only the basics, the extensive documentation and vibrant community surrounding Three.js offer a wealth of knowledge and resources to help you on your journey. Dive in, experiment, and see what incredible 3D experiences you can create for the web.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c803098d3217" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/exploring-three-js-for-3d-web-development-c803098d3217">Exploring Three.js for 3D Web Development</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js Large file uploads using Edge Store]]></title>
            <link>https://medium.com/codeparrot-ai/next-js-large-file-uploads-using-edge-store-6793e399a9ca?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6793e399a9ca</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Wed, 01 May 2024 13:16:19 GMT</pubDate>
            <atom:updated>2024-05-01T13:16:19.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eAir3BxlooZxrjT5xtHCg.png" /></figure><blockquote>Handling file uploads in Next.js requires setting up a server to manage these uploads. This process can be time-consuming and prone to errors, which poses a challenge for developers looking to create efficient and reliable applications when dealing with large files or low network conditions.</blockquote><blockquote><em>Resources: </em><a href="https://github.com/harshalranjhani/edgestore-resources"><em>https://github.com/harshalranjhani/edgestore-resources</em></a></blockquote><h3>The Current State of File Uploads in Next.js</h3><p>Handling file uploads in Next.js requires setting up a server to manage these uploads and writing a significant amount of boilerplate code. This process can be time-consuming and prone to errors, which poses a challenge for developers looking to create efficient and reliable applications when dealing with large files or low network conditions.</p><h3>What is EdgeStore?</h3><p>EdgeStore is a type-safe Node package that makes it super easy to upload and retrieve files from the cloud. It’s designed to cut down on the setup or configuration time, letting you say goodbye to all that extra boilerplate code you’d normally have to write for cloud file uploads. With EdgeStore, managing cloud files becomes straightforward, freeing you up to focus more on building great features for your app.</p><h3>Using Edgestore in a Next.js project</h3><p>First let’s start by initializing a Next.js project:</p><pre>npx create-next-app@latest # yarn create next-app</pre><p>After you’re done setting up the Next.js project, you’ll be prompted with a few questions, I would suggest going with all the default options, only that we’ll be using Typescript in this article, since edgestore is type-safe, why not utilize that right?</p><p>Now enter inside your app and install all the dependencies:</p><pre>npm install # yarn</pre><p>Now we will install the dependencies required by edgestore:</p><pre>npm install @edgestore/server @edgestore/react zod # yarn add @edgestore/server @edgestore/react zod</pre><p>We will start by creating a new account on <a href="https://dashboard.edgestore.dev/sign-up">edgestore</a>. After you’re successfully signed up, you can head over to your <a href="https://dashboard.edgestore.dev/">dashboard</a> where you can create a new project. After creating a new project you will have access to a access key and a secret key.</p><p>Add these keys to your .env.local file:</p><pre>EDGE_STORE_ACCESS_KEY=your-access-key<br>EDGE_STORE_SECRET_KEY=your-secret-key</pre><p>Next, create a folder named api inside the src/app directory.</p><p>Now create a new file route.ts inside the src directory at the location src/app/api/edgestore/[...edgestore]:</p><p>Copy the following into route.ts:</p><pre>import { initEdgeStore } from &quot;@edgestore/server&quot;;<br>import { createEdgeStoreNextHandler } from &quot;@edgestore/server/adapters/next/app&quot;;<br>const es = initEdgeStore.create();</pre><pre>const edgeStoreRouter = es.router({<br>  publicFiles: es.fileBucket({<br>    maxSize: 1024 * 1024 * 10, // 10MB<br>    // accept: [&quot;application/pdf&quot;],<br>  }),<br>});</pre><pre>const handler = createEdgeStoreNextHandler({<br>  router: edgeStoreRouter,<br>});</pre><pre>export { handler as GET, handler as POST };</pre><pre>export type EdgeStoreRouter = typeof edgeStoreRouter;</pre><p>Here I’ve created a file upload bucket where the maximum upload size is 10mb and additionally you can also specify the file extensions to be accepted.</p><p>For images, edgestore provides a dedicated bucket called imageBucket which you can replace with fileBucket to dedicate it for images.1</p><p>Now we will set up the context provider for our frontend: For this we create a new file called edgestore.ts inside src/lib:</p><p>Copy the following into layout.tsx:</p><pre>&quot;use client&quot;;<br>import { type EdgeStoreRouter } from &quot;../app/api/edgestore/[...edgestore]/route&quot;;<br>import { createEdgeStoreProvider } from &quot;@edgestore/react&quot;;<br>const { EdgeStoreProvider, useEdgeStore } =<br>  createEdgeStoreProvider&lt;EdgeStoreRouter&gt;();<br>export { EdgeStoreProvider, useEdgeStore };</pre><p>And then we can wrap our app with the EdgeStoreProvider. Copy the following into src/app/layout.tsx:</p><pre>import { EdgeStoreProvider } from &quot;../lib/edgestore&quot;;<br>import &quot;./globals.css&quot;;</pre><pre>// ...</pre><pre>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;EdgeStoreProvider&gt;{children}&lt;/EdgeStoreProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>We can use the useEdgeStore hook to directly upload files from the frontend.</p><p>Inside your page.tsx copy the following:</p><pre>&quot;use client&quot;;</pre><pre>// ..</pre><pre>import { useEdgeStore } from &quot;../lib/edgestore&quot;;</pre><pre>export default function Page() {<br>  // .. state declarations</pre><pre>  const { edgestore } = useEdgeStore();</pre><pre>  return (<br>    &lt;div className=&quot;m-20&quot;&gt;<br>      &lt;input<br>        type=&quot;file&quot;<br>        onChange={(e) =&gt; {<br>          setFile(e.target.files?.[0]);<br>        }}<br>      /&gt;<br>      &lt;button<br>        onClick={async () =&gt; {<br>          setUrl(null);<br>          if (file) {<br>            const res = await edgestore.publicFiles.upload({<br>              file,<br>              onProgressChange: (progress) =&gt; {<br>                // you can use this to show a progress bar<br>                console.log(progress);<br>                setProgress(progress);<br>              },<br>            });<br>            // you can run some server action or api here<br>            // to add the necessary data to your database<br>            console.log(res);<br>            setUrl(res.url);<br>            setProgress(null);<br>          }<br>        }}<br>      &gt;<br>        Upload<br>      &lt;/button&gt;<br>      &lt;div className=&quot;mt-10&quot;&gt;<br>        {progress !== null &amp;&amp; &lt;div&gt;Progress: {progress}%&lt;/div&gt;}<br>        {url &amp;&amp; (<br>          &lt;div&gt;<br>            URL: &lt;Link href={url}&gt;{url}&lt;/Link&gt;<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>After this you can try to upload a sample file and you should see something like this after the successful upload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MOFQu5wNqIEV4zVL" /></figure><p>And that’s it! It’s actually lightning fast and super easy to upload files to the cloud without having to setup formData or any API logic!</p><h3>Some more functions that edgestore provides</h3><h4>Replace file</h4><p>You can replace an already uploaded file by passing the replaceTargetUrl option. The old file will be automatically deleted after the upload.</p><pre>const res = await edgestore.publicFiles.upload({<br>  file,<br>  options: {<br>    replaceTargetUrl: oldFileUrl,<br>  },<br>  // ...<br>});</pre><h4>Temporary files</h4><p>Edgestore provides us the option to store temporary files which if not confirmed are deleted within 24 hours.</p><p>To upload a temporary file simply add the following to your options:</p><pre>options: {<br>  // ..<br>  temporary: true,<br>},</pre><p>To confirm a temporary file:</p><pre>await edgestore.publicFiles.confirmUpload({<br>  url: urlToConfirm,<br>});</pre><h4>Download files</h4><p>Sometimes the browser displays the file instead of downloading it forcefully, if you want to force that download, use getDownloadUrl:</p><pre>import { getDownloadUrl } from &quot;@edgestore/react/utils&quot;;</pre><pre>getDownloadUrl(<br>  url, // the url of the file to download<br>  &quot;example.pdf&quot; // optional, the name of the file to download<br>);</pre><h3>Conclusion</h3><p>When it comes to getting your Next.js apps up and running quickly with file storage, Edgestore is a terrific solution. Many configuration choices covering a wide range of use-cases have been offered which make it super easy to use.</p><p>Edge Store’s integration with Next.js is a step towards the development of web apps that are user-focused, user-friendly, and faster in the future.</p><p>Read more and discover the full potential of Edge Store by visiting the <a href="https://edgestore.dev/docs/quick-start">official documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6793e399a9ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/next-js-large-file-uploads-using-edge-store-6793e399a9ca">Next.js Large file uploads using Edge Store</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preact: Lightweight React Alternative]]></title>
            <link>https://medium.com/codeparrot-ai/preact-lightweight-react-alternative-66e066b47928?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/66e066b47928</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[preact]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Wed, 01 May 2024 09:03:21 GMT</pubDate>
            <atom:updated>2024-05-01T09:03:21.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbEYHj6hkbt1d0yRX9Qa9g.png" /><figcaption>Preact: React Alternative</figcaption></figure><blockquote>Exploring Preact’s Advantages in Performance and Size for Enhanced Web Development</blockquote><h3>What is Preact?</h3><h4>Definition and Core Features</h4><p>Preact is a fast, lightweight JavaScript library that describes itself as a “fast 3kB alternative to React with the same modern API.” But what does this mean for you as a developer? At its core, Preact offers the same capabilities as React: it allows you to create interactive UIs, manage component-based architecture, and handle state and props efficiently. However, it does this with a significantly smaller footprint, making it a compelling choice for performance-focused projects.</p><h4>Comparison with React: Size and Performance Benefits</h4><p>One of the most notable differences between Preact and React is the size. Preact’s package is about 3kB when minified and gzipped, compared to React’s 45kB. This stark difference can lead to faster load times, which is crucial for improving user experience, particularly on mobile devices and in areas with slower internet connections.</p><p>Performance-wise, Preact is designed to be as efficient as possible. It achieves this through a simplified virtual DOM architecture, which can lead to faster rendering times. This efficiency doesn’t come at the cost of re-learning a new framework; Preact prides itself on its similarity to React, making it an easy transition for those already familiar with React’s principles.</p><h3>Why Consider Preact?</h3><h4>Advantages of Preact over React</h4><p><strong>Performance Improvements:</strong> Preact’s small size directly translates into performance gains, particularly in the initial load time. For applications where speed is a priority, this can be a significant advantage.</p><p><strong>Smaller Bundle Size:</strong> The reduced size of Preact makes it ideal for projects where bandwidth usage is a concern, such as mobile applications or web apps targeted at regions with limited internet connectivity.</p><p><strong>Easier Integration:</strong> Preact’s API is nearly identical to React’s, which means integrating it into existing projects is relatively straightforward. This is especially beneficial for developers looking to improve performance without a complete overhaul of their codebase.</p><h4>When to Use Preact</h4><p>Preact is particularly well-suited for:</p><ul><li>Projects where performance, particularly load time, is critical.</li><li>Applications that need to be lightweight, such as mobile web apps.</li><li>Situations where you want to incrementally improve an existing React codebase.</li></ul><h3>React Vs Preact</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dwh98yfSOU9-F65Pv4l1Dw.png" /></figure><h3>Getting Started with Preact</h3><h4>Setting Up a Basic Preact Application</h4><p>To start using Preact, you need to set up your development environment. This is quite simple:</p><pre>npx create-preact-app my-preact-app <br>cd my-preact-app <br>npm install <br>npm run dev</pre><p>This sets up a basic Preact project similar to ‘create-react-app’ for React.</p><h4>Basic Hello World Example</h4><pre>import { h, render } from &#39;preact&#39;;</pre><pre>function App() {<br>  return &lt;h1&gt;Hello, Preact!&lt;/h1&gt;;<br>}</pre><pre>render(&lt;App /&gt;, document.getElementById(&#39;app&#39;));</pre><p>Here’s a simple example of a Preact component:</p><p>This code snippet demonstrates the basic structure of a Preact component, which should be familiar if you’ve worked with React.</p><h3>Best Practices in Preact Development</h3><p>When developing with Preact, employing best practices not only ensures optimal performance but also maintains the readability and scalability of your code. Here are some recommended best practices:</p><ul><li><strong>Component Composition</strong>: Favor composition over inheritance. Create small, reusable components that can be combined in various ways to build complex UIs.</li><li><strong>Immutable Data Patterns</strong>: Use immutable data structures to improve performance and predictability of your state management.</li><li><strong>Efficient State Updates</strong>: Be mindful of unnecessary re-renders. Use Preact’s shouldComponentUpdate lifecycle method or hooks to control your component&#39;s update lifecycle.</li><li><strong>Code Splitting</strong>: Implement code splitting to load only the necessary code, reducing the time to interactive for your app. Preact supports this out of the box with its preact/async-route component.</li><li><strong>Use Functional Components</strong>: Whenever possible, use functional components with hooks to manage state and side effects, which are more lightweight and often result in cleaner code.</li></ul><h3>Advanced Features of Preact</h3><ul><li><strong>Preact CLI</strong>: Preact comes with a command-line tool that scaffolds your project and provides automatic code splitting, server-side rendering, and progressive web application (PWA) capabilities.</li><li><strong>Preact Hooks</strong>: While React introduced Hooks in version 16.8, Preact has adopted this feature, allowing you to use state and other React features without writing a class.</li><li><strong>Preact X</strong>: The tenth version of Preact brought in hooks, and several other improvements like improved fragment support, and the suspense component which allows for asynchronous rendering.</li><li><strong>Integration with Other Libraries</strong>: Preact can be seamlessly integrated with state management libraries such as Redux or MobX, and even with routing libraries like React Router, by using the appropriate compatibility layer.</li></ul><h3>Migrating from React to Preact</h3><h4>Step-by-Step Guide on Migrating</h4><p>Migrating from React to Preact is relatively straightforward due to their similar APIs. The key steps involve:</p><ol><li>Replacing react and react-dom with preact/compat in your project dependencies.</li><li>Adjusting any direct dependencies on React internal APIs, if used, as they might not be supported in Preact.</li></ol><h4>Key Differences to Keep in Mind</h4><p>While Preact aims to be as compatible as possible with React, there are some differences:</p><ul><li>Certain less commonly used React features (like Suspense and Concurrent Mode) might not be available or behave differently.</li><li>Preact’s handling of this.props, this.state, and setState() can have subtle differences.</li></ul><h3>Case Studies</h3><p>Preact has been successfully used in various projects, ranging from small personal blogs to large-scale commercial applications. Examples include:</p><ul><li><a href="https://eng.uber.com/m-uber/">Uber’s web app</a>, which used Preact for its lightweight nature.</li><li>Numerous open-source projects on GitHub that demonstrate its efficiency in real-world scenarios.</li></ul><h3>Resources and Further Learning</h3><p>To delve deeper into Preact, check out:</p><ul><li>The <a href="https://preactjs.com/">official Preact documentation</a>.</li><li>Tutorials and courses available online, which provide hands-on experience with Preact.</li></ul><h3>Conclusion</h3><p>As we’ve explored throughout this blog, the choice between Preact and React hinges on the specific needs and priorities of your project. Preact stands out as an excellent choice for projects where speed and optimization are paramount. Its smaller bundle size and faster virtual DOM implementation make it ideal for applications where performance is a critical factor, especially in environments with bandwidth constraints or on devices with limited resources.</p><p>On the other hand, React, with its more feature-rich and flexible API, remains the go-to option for more complex and intricate projects. The breadth and depth of React’s API cater to a wider range of use cases, especially when the project involves complex state management or integration with a vast ecosystem of libraries and tools.</p><p>In essence, the decision between React and Preact is not about which is universally better, but rather which is more suited to the unique requirements of your project. Preact is an excellent choice for performance-centric applications, while React continues to excel in scenarios that demand a more comprehensive set of features and capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66e066b47928" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/preact-lightweight-react-alternative-66e066b47928">Preact: Lightweight React Alternative</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build component library using Storybook]]></title>
            <link>https://medium.com/codeparrot-ai/build-component-library-using-storybook-e2ac67e078fd?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2ac67e078fd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 21:34:36 GMT</pubDate>
            <atom:updated>2024-04-04T21:34:36.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MsITds0BJEFPS92y8ZWOw.png" /><figcaption>storybook</figcaption></figure><p>Storybook is an open-source tool for UI development that allows developers to build UI component library in isolation. Why and how to use it.</p><p>It serves as a “workshop” environment where you can see how components look and behave in various states without needing to embed them in your application’s main UI. This makes it easier to develop, test, and document components. Why should you use it?</p><ul><li><strong>Isolation</strong>: Develop components in isolation, which means that changes in one component won’t affect others. Which means that to see how components look and behave in various states, we don’t need to embed them and navigate to that particular user journey. Look at storybook for popular video sdk, Agora. You can see each component and the states / controls it provides</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4cftfUot0yBaHn7n.png" /><figcaption>Agora Storybook</figcaption></figure><p>You can see their entire storybook <a href="https://netless-io.github.io/flat/?path=/story/chatpanel-chatmessage--overview&amp;globals=locale:en">here</a></p><ul><li><strong>Documentation</strong>: Generate documentation automatically, making it easier to share how components should be used. Often other developers are unaware of pre-existing components and end up creating their own version, which becomes a maintenance challenge.</li><li><strong>Interactive Playground</strong>: Provides an interactive UI to play with component properties (knobs).</li><li><strong>Visual Testing</strong>: Supports visual regression testing to catch visual bugs. Often visual regressions are hard to test with traditional e2e testing, visual testing helps in removing the manual inspection</li></ul><h3>Getting Started with Storybook</h3><p>To start using Storybook, you typically integrate it into a project that’s already set up with a UI framework like React, Vue, or Angular. Here’s how you can set it up in a React project:</p><ol><li><strong>Install Storybook: </strong>If you have a React project set up, you can add Storybook by running the following command in your project directory:</li></ol><pre>npx sb init</pre><p><strong>2. Run Storybook: </strong>After installation, you can start the Storybook server with:</p><pre>npm run storybook</pre><p>This command will start the Storybook environment on a local server, typically accessible at <a href="http://localhost:6006/">http://localhost:6006</a>.</p><p><strong>3. Create a Story: </strong>Stories in Storybook are JavaScript modules that define how to render a component. You write stories to display each state of your UI components. Here’s an example of a story for a simple Button component in a React project:</p><pre>// Button.stories.js <br><br>import React from &#39;react&#39;; <br>import { Button } from &#39;./Button&#39;;  <br><br>export default {   title: &#39;Button&#39;,   component: Button, };  <br><br>export const Primary = () =&gt; &lt;Button primary&gt;Click me&lt;/Button&gt;; <br>export const Secondary = () =&gt; &lt;Button&gt;Click me&lt;/Button&gt;;</pre><p>In this code:</p><ul><li>title defines the name of the component group in the Storybook UI.</li><li>component is the actual component being documented.</li><li>Primary and Secondary are variations of the Button component, known as &quot;stories&quot;.</li></ul><p><strong>4. View Your Components in Storybook: </strong>Once Storybook is running, you can navigate to its web interface where you will see the stories defined in your project. You can click on each story to view the rendered component and interact with it.</p><h3>Documentation using Storybook</h3><p>Storybook uses a feature called DocsPage to automatically generate documentation from your stories and code comments. Additionally, you can enhance documentation with Markdown or MDX (Markdown with JSX) to write narrative documentation.</p><p>Here’s how you can document your components in Storybook:</p><h3>1. Set Up Documentation</h3><p>Ensure that @storybook/addon-docs is installed and configured in your Storybook setup. This addon is often included by default when you initialize Storybook in your project. It parses your component and its comments to generate documentation.</p><h3>2. Write Component Comments</h3><p>Use JSDoc style comments in your component code to document props, states, and any other relevant information. Storybook’s Docs addon can then automatically generate documentation from these comments.</p><p>For example:</p><pre>// Button.js<br><br>/**<br> * Primary UI component for user interaction.<br> *<br> * @param {Object} props - Props for button<br> * @param {string} props.label - The text that the button will display<br> * @param {function} props.onClick - The callback function to call on button click<br> * @param {boolean} [props.disabled=false] - Whether the button is disabled<br> */<br>const Button = ({ label, onClick, disabled = false }) =&gt; (<br>    &lt;button disabled={disabled} onClick={onClick}&gt;<br>        {label}<br>    &lt;/button&gt;<br>);<br><br>export default Button;</pre><h3>3. Create Stories with Args</h3><p>In your stories, define args for your component to show different states and prop configurations. Storybook will use these args to render controls and actions in the DocsPage.</p><pre>// Button.stories.js<br>import React from &#39;react&#39;;<br>import Button from &#39;./Button&#39;;<br>export default {<br>  title: &#39;Components/Button&#39;,<br>  component: Button,<br>};<br><br>const Template = (args) =&gt; &lt;Button {...args} /&gt;;<br>export const Primary = Template.bind({});<br>Primary.args = {<br>  label: &#39;Click Me&#39;,<br>  disabled: false,<br>  onClick: () =&gt; alert(&#39;Clicked!&#39;),<br>};</pre><h3>4. Enhance with MDX</h3><p>For more detailed documentation, you can use MDX. Create an MDX file where you can mix Markdown text with live Storybook previews.</p><pre>// Button.stories.mdx<br>import { Meta, Story, ArgsTable, Canvas } from &#39;@storybook/addon-docs&#39;;<br>import Button from &#39;./Button&#39;;<br>&lt;Meta title=&quot;Components/Button&quot; component={Button} /&gt;<br><br># Button Component<br>The Button component is used for user interactions.<br>## Props<br>&lt;ArgsTable of={Button} /&gt;<br>## Usage<br>&lt;Canvas&gt;<br>  &lt;Story name=&quot;Primary&quot; args={{ label: &#39;Hello&#39;, disabled: false }}&gt;<br>    {Template}<br>  &lt;/Story&gt;<br>&lt;/Canvas&gt;</pre><p>In this MDX file, Meta sets the component metadata, ArgsTable generates a table of the component&#39;s props, and Canvas and Story are used to render live previews.</p><h3>5. Run and Review</h3><p>Run Storybook to see your documentation in action. Navigate to your component in the Storybook UI, and you should see the generated DocsPage with your component’s documentation, including the interactive props table and live examples. Documentation makes it easier for developers to understand and use your component library effectively.</p><p>Storybook offers a robust platform for building, documenting, and testing UI components in isolation. By integrating Storybook into your development workflow, you can create a well-structured, easily navigable, and thoroughly documented component library. This not only speeds up the development process but also ensures a consistent design and user experience across your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2ac67e078fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/build-component-library-using-storybook-e2ac67e078fd">Build component library using Storybook</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Web Vitals: Rank your websites higher on SEO]]></title>
            <link>https://medium.com/codeparrot-ai/core-web-vitals-rank-your-websites-higher-on-seo-29a2e7cba49c?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a2e7cba49c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 07:35:46 GMT</pubDate>
            <atom:updated>2024-03-28T07:35:46.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Core Web Vitals" src="https://cdn-images-1.medium.com/max/1024/1*fwggRwZ5oKaHd2os9huUiQ.jpeg" /><figcaption>Core Web Vitals</figcaption></figure><h4>Core Web Vitals are metrics that Google uses to measure the user experience of a webpage. They are an important factor in search engine ranking (SEO)</h4><p>Google’s Web Vitals initiative, aims to provide quality metrics essential to delivering a great user experience on the web. A website that performs well on these metrics generally offers a smooth experience for users, which can lead to longer visit durations, higher levels of engagement, and increased conversions. Google incorporates these vitals in its search engine ranking to ensure websites with better experience rank higher. There are many signals but three most important, also known as Core Web Vitals are:</p><ol><li><strong>Largest Contentful Paint (LCP)</strong>: Measures the loading performance of a webpage. Specifically, it marks the point in the page load timeline when the largest text or image content has been rendered. A good LCP time is considered to be 2.5 seconds or faster.</li><li><strong>First Input Delay (FID)</strong>: Measures the interactivity and responsiveness of a webpage. It captures the time from when a user first interacts with a page (e.g., clicking a link, tapping on a button) to the time when the browser is actually able to respond to that interaction. A good FID time is less than 100 milliseconds.</li><li><strong>Cumulative Layout Shift (CLS)</strong>: Measures the visual stability of a webpage. It quantifies the amount of unexpected layout shift of visible page content. A low CLS score indicates that the page is stable and content does not shift in a way that can be disorienting for users. A good CLS score is less than 0.1.</li></ol><p>We’ll look at each in detail now</p><h3>Largest Contentful Paint</h3><figure><img alt="Largest Contentful Paint" src="https://cdn-images-1.medium.com/max/1024/1*Ken-tP8pLkDlWn0IkHzB-w.jpeg" /><figcaption>Largest Contentful Paint</figcaption></figure><p>Largest Contentful Paint (LCP) is a metric that measures the loading performance of a webpage, specifically the time it takes for the largest content element visible in the viewport to fully load and be ready for user interaction. It’s a critical factor in determining the perceived speed of a website.</p><h4>Examples and Images</h4><ul><li><strong>Image-heavy Website</strong>: On a photography website, the LCP might be the time it takes for the largest photograph on the homepage to load. If this photograph is very large in file size, it can significantly delay the LCP.</li><li><strong>Text-heavy Blog</strong>: On a blog, the LCP might be the largest block of text visible to the user when the page first loads. If this text is part of a large article or includes heavy fonts, it can impact the LCP.</li><li><strong>E-commerce Site</strong>: For an e-commerce site, the LCP could be the main hero image or a large product image on the homepage. The faster this image loads, the quicker the user perceives the page as usable.</li></ul><h4>Best Practices</h4><ol><li><strong>Optimize Images</strong>: Compress images without losing quality to reduce their file size. Use modern, efficient image formats like WebP. Ensure images are responsive and load different sizes based on the user’s device to save bandwidth.</li><li><strong>Prioritize Loading of Important Assets</strong>: Use resource hints such as preload to inform the browser about critical resources that need to be loaded first. This can ensure that the largest content element is loaded quickly.</li><li><strong>Remove Unnecessary Third-Party Scripts</strong>: Third-party scripts can slow down your site. Evaluate and keep only essential third-party resources, or defer the loading of non-critical scripts until after the main content has loaded.</li><li><strong>Use a Content Delivery Network (CDN)</strong>: A CDN can serve your content from a server location closer to the user, reducing the time it takes for the largest contentful element to load.</li></ol><h3>First Input Delay (FID)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfpjHQTWLKAk1zwuxZdUzQ.jpeg" /><figcaption>First Input Delay</figcaption></figure><p>First Input Delay (FID) is a performance metric that measures the time from when a user first interacts with a page (like clicking a link, tapping a button, or using a custom, JavaScript-powered control) to the time when the browser is actually able to begin processing event handlers in response to that interaction.</p><h4>Examples</h4><ol><li><strong>Button Click</strong>: When a user clicks a button to submit a form, FID measures the time from the user’s click to the browser’s response to that click. If there’s a delay in processing the click because the main thread is busy, the FID will be high.</li><li><strong>Navigation</strong>: When a user selects a new page from a navigation menu, FID measures the delay before the browser starts loading the new page. If the browser is busy executing heavy JavaScript, the user might experience a noticeable delay.</li><li><strong>Interacting with a JavaScript-driven element</strong>: For example, expanding a dropdown menu or interacting with a slider on a webpage. If the JavaScript is complex and the browser is busy, there could be a delay in expanding the dropdown or moving the slider, leading to a higher FID.</li></ol><h4>Best Practices</h4><ul><li><strong>Minimize JavaScript Execution Time</strong>: Break up long tasks into smaller, asynchronous tasks to reduce the time the main thread is blocked, allowing it to respond more quickly to user inputs.</li><li><strong>Optimize Page Load</strong>: Ensure that the critical path resources are loaded first and defer non-critical resources. This allows the browser to become interactive more quickly.</li><li><strong>Use Web Workers</strong>: Move non-UI operations to a web worker to run them in a background thread, keeping the main thread free to respond to user input.</li><li><strong>Avoid Large JavaScript Bundles</strong>: Splitting JavaScript bundles into smaller chunks ensures that only the necessary code is parsed and compiled on the page the user is interacting with, reducing the load on the main thread.</li><li><strong>Prioritize Interactive Elements</strong>: Ensure that interactive elements like buttons or input fields are interactive early in the page load process, so users can interact with them without delay.</li></ul><h3>Cumulative Layout Shift (CLS)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88f0ItVV3rEgaQUv5arZzg.jpeg" /><figcaption>Cumulative Layout Shift</figcaption></figure><p>Cumulative Layout Shift (CLS) is a metric that measures the visual stability of a website. It quantifies how much the content on the page shifts unexpectedly during the loading phase. High CLS values indicate that elements on the page are moving around a lot as the page loads, which can lead to a poor user experience.</p><h4>How CLS is Measured</h4><p>CLS is calculated by multiplying the impact fraction (the area of the viewport that shifts) by the distance fraction (the distance that the unstable elements move). This calculation is done for each unexpected layout shift that occurs throughout the entire lifespan of the page, and the individual scores are summed to get the final CLS score.</p><h4>Examples of Layout Shifts</h4><ol><li><strong>Images without dimensions</strong>: If an image loads without predefined width and height attributes, it can push content down or to the side once it loads, causing a layout shift.</li><li><strong>Ads, embeds, and iframes without dimensions</strong>: Similar to images, these elements can load at different times and change the size of the space they occupy, shifting content unexpectedly.</li><li><strong>Dynamically injected content</strong>: Content added to the page dynamically, like a newsletter sign-up banner or an alert message, can push other content down or to the side.</li><li><strong>Web Fonts causing FOIT/FOUC</strong>: Flash of Invisible Text (FOIT) or Flash of Unstyled Content (FOUC) can occur when custom fonts load after the rest of the content, causing a shift.</li></ol><h4>Best Practices for Reducing CLS</h4><ul><li><strong>Specify size attributes for images and videos</strong>: Always include width and height attributes for media elements to ensure the browser can allocate the correct amount of space while the media is loading.</li><li><strong>Ensure ad elements have a reserved space</strong>: Predefine the size of ad slots so that when they load, they do not cause content to shift.</li><li><strong>Avoid inserting new content above existing content</strong>: Be cautious about dynamically injecting content, especially if it affects the current layout significantly.</li><li><strong>Use CSS aspect ratio boxes</strong>: For elements that don’t have an intrinsic size, use the aspect ratio property in CSS to reserve space based on the ratio of the width and height.</li><li><strong>Preload fonts</strong>: Use font-display: swap or preload your fonts to avoid FOIT/FOUC, which can cause layout shifts when the font finally loads.</li></ul><p>You can use <a href="https://pagespeed.web.dev/">https://pagespeed.web.dev/</a> to check and improve the web vitals of your website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a2e7cba49c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/core-web-vitals-rank-your-websites-higher-on-seo-29a2e7cba49c">Core Web Vitals: Rank your websites higher on SEO</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies in Depth using Javascript and NodeJs]]></title>
            <link>https://medium.com/codeparrot-ai/cookies-in-depth-using-javascript-and-nodejs-a0d55f4a4c06?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d55f4a4c06</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 08:18:42 GMT</pubDate>
            <atom:updated>2024-03-22T08:18:42.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1eEf83D_JU5t-2KtYmBOQ.png" /><figcaption>Cookies in Depth</figcaption></figure><p>Cookies are used for personalisation, tracking &amp; advertising. Understand why cookies are needed and how to implement them using Javascript and NodeJs</p><h3>What are Cookies?</h3><p>Cookies are small pieces of data stored on a user’s web browser. They are used to remember stateful information (such as items added in the shopping cart in an online store) or to record the user’s browsing activity (like recording which pages were visited in the past).</p><p>There are different types of cookies:</p><ul><li><strong>Session cookies</strong>: Temporary cookies that expire once you close your browser. They are used to track user activity during a single session like e-com websites use session cookies to track users’ shopping cart items as they browse different pages of the site.</li><li><strong>Persistent cookies</strong>: These remain on your device for a set period specified in the cookie. They are used to remember your preferences like news websites use persistent cookies to store preferred language, region, or layout settings.</li><li><strong>Third-party cookies</strong>: Placed by a website other than the one you are currently visiting, these are often used for advertising and tracking across multiple websites. Ever searched for Ipad on Amazon and started seeing ads on other websites? That’s third party cookies</li></ul><h3>Why are Cookies Useful?</h3><ol><li><strong>Session management</strong>: They help manage user sessions, allowing websites to recognize users and their preferences as they navigate through the site. This includes keeping users logged in, tracking their progress through a site, and storing items in a shopping cart.</li><li><strong>Personalization</strong>: Cookies store user preferences and settings to customize the user experience on a website. This can include language settings, themes, and other personalization details.</li><li><strong>Tracking and analytics</strong>: Websites use cookies to gather data about user behavior, such as the pages visited, time spent on the site, and interaction with content. This information helps website owners understand how users interact with their site, allowing for improvements and more targeted content or advertisements.</li><li><strong>Advertising</strong>: Cookies are used to deliver targeted advertisements to users based on their browsing history and preferences. They help advertisers show relevant ads to users and track the performance of ad campaigns.</li></ol><h3>Implementing Cookies</h3><p>Cookies can be implemented on both client and server side.</p><h3>Client Side (Javascript)</h3><p><strong>Creating Cookie:</strong> To create a cookie, you assign a string to document.cookie that contains the cookie name, value, and optionally other attributes like expiration, path, domain, secure, and SameSite. For example:</p><pre>document.cookie = &quot;username=JohnDoe; expires=Thu, 31 Dec 2029 23:59:59 GMT; path=/&quot;;</pre><p>This line creates a cookie named username with the value JohnDoe that expires on December 31, 2029, and is accessible to all pages within the domain.</p><p><strong>Reading Cookie:</strong> To read cookies, you access the document.cookie property, which returns all cookies for the current domain as a string. You then need to parse this string to find the value of the specific cookie you are interested in. For example:</p><pre>var cookieValue = document.cookie<br>  .split(&#39;; &#39;)<br>  .find(row =&gt; row.startsWith(&#39;username=&#39;))<br>  ?.split(&#39;=&#39;)[1];</pre><p>This code snippet finds the username cookie and retrieves its value.</p><h3>Server Side (Node.js)</h3><p><strong>Setup:</strong> In your project, create a file named server.js (or another name of your choice) and install basic Express server, along with cookie-parser library to handle cookies easily</p><pre>npm install express cookie-parser</pre><p>Then, you can use it in your Express application to read and set cookies.</p><pre>// Import the required modules<br>const express = require(&#39;express&#39;);<br>const cookieParser = require(&#39;cookie-parser&#39;);<br><br>// Initialize the express application<br>const app = express();<br>// Use the cookie-parser middleware<br>app.use(cookieParser());<br>// Route to set a cookie<br>app.get(&#39;/set-cookie&#39;, (req, res) =&gt; {<br>    // Set a cookie named &#39;user&#39; with a value of &#39;John Doe&#39;<br>    res.cookie(&#39;user&#39;, &#39;John Doe&#39;, { maxAge: 900000, httpOnly: true });<br>    res.send(&#39;Cookie has been set&#39;);<br>});<br>// Route to get the cookie value<br>app.get(&#39;/get-cookie&#39;, (req, res) =&gt; {<br>    // Access the cookie named &#39;user&#39;<br>    let userCookie = req.cookies.user;<br>    if (userCookie) {<br>        res.send(`Cookie value: ${userCookie}`);<br>    } else {<br>        res.send(&#39;No cookie found&#39;);<br>    }<br>});<br><br>// Start the server<br>const PORT = 3000;<br>app.listen(PORT, () =&gt; {<br>    console.log(`Server is running on http://localhost:${PORT}`);</pre><p>In this example:</p><ul><li>The /set-cookie route sets a cookie named user with the value John Doe</li><li>The /get-cookie route reads the value of the user cookie and sends it in the response</li><li>The cookie-parser middleware is used to parse the cookies attached to the client request object</li></ul><p>Run your server using the command node server.js, and then visit <a href="http://localhost:3000/set-cookie">http://localhost:3000/set-cookie</a> in your browser to set the cookie, and <a href="http://localhost:3000/get-cookie">http://localhost:3000/get-cookie</a> to retrieve and display the cookie value.</p><h3>Cookies vs Local Storage</h3><p>Cookies and local storage are both used to store data on the client’s side in web applications, but they serve different purposes and have different characteristics:</p><ul><li><strong>Storage Size</strong>: Local storage can hold more data compared to cookies.</li><li><strong>Lifespan</strong>: Cookies can be set to expire; local storage data stays until it is cleared.</li><li><strong>Server Interaction</strong>: Cookies are sent with every request to the server, whereas local storage data stays on the client-side.</li><li><strong>Scope</strong>: Cookies are accessible by both client and server; local storage is strictly client-side.</li></ul><p>In summary, cookies are better suited for smaller amounts of data that need to be sent to the server with each request, while local storage is more appropriate for storing larger amounts of data that don’t need to be sent to the server and should persist beyond the session.</p><h3>Be Careful</h3><p>When maintaining cookies, there are several important points to consider to ensure security, privacy, and a good user experience:</p><ol><li><strong>Security</strong></li></ol><ul><li>Use the Secure attribute to ensure cookies are sent over HTTPS, protecting them from being intercepted during transmission.</li><li>Set the HttpOnly attribute to prevent client-side scripts from accessing the cookie, reducing the risk of cross-site scripting (XSS) attacks.</li><li>Consider using the SameSite attribute to control how cookies are sent with cross-site requests, which can help prevent cross-site request forgery (CSRF) attacks.</li></ul><p><strong>2. Privacy and Compliance</strong>:</p><ul><li>Privacy laws and regulations, such as the General Data Protection Regulation (GDPR) in the EU, require obtaining consent from users before storing cookies that track information.</li><li>Offer users the ability to choose which cookies they want to allow (e.g., essential, analytics, marketing) and provide an easy way to change their preferences.</li></ul><p><strong>3. Expiration and Management</strong>:</p><ul><li>Set an appropriate expiration date for cookies. Session cookies expire when the browser is closed, while persistent cookies last until their expiration date.</li><li>Regularly review and clean up unused or old cookies to avoid unnecessary data retention and potential security risks.</li></ul><p><strong>4. Domain and Path Attributes</strong>:</p><ul><li>Specify the Domain and Path attributes correctly to control which domains and paths in your site can access the cookies, preventing them from being sent to or accessed by unintended parts of your site or application.</li></ul><p><strong>5. Data Sensitivity and Storage</strong>:</p><ul><li>Avoid storing sensitive information (such as passwords, personal identification information, or credit card numbers) directly in cookies due to the risk of interception or unauthorized access.</li><li>Consider encrypting cookie values to protect the data they contain, especially if they are used for authentication or session management.</li></ul><p><strong>6. Performance</strong>:</p><ul><li>Be mindful of the size and number of cookies used, as each cookie is sent with every HTTP request to the domain, which can affect performance, especially on mobile networks.</li></ul><p><strong>7. Cross-Site Tracking</strong>:</p><ul><li>Be cautious with third-party cookies, as they can be used for tracking user behavior across different sites. Their use is increasingly being restricted by browser privacy features and regulations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d55f4a4c06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/cookies-in-depth-using-javascript-and-nodejs-a0d55f4a4c06">Cookies in Depth using Javascript and NodeJs</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vite: 90% faster Webpack alternative]]></title>
            <link>https://medium.com/@royaljain0203/vite-90-faster-webpack-alternative-7eeba6e284af?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eeba6e284af</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vitejs]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 06:50:37 GMT</pubDate>
            <atom:updated>2024-03-21T06:50:37.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mbZAaHee_Rh-zkkq" /><figcaption>Vite: Faster Webpack Alternative</figcaption></figure><p>Vite is a cutting-edge build tool that harnesses the power of ES modules to serve your code with lightning-fast server start-up time and seamless hot module replacement (HMR). Why Opt for Vite? 🤔</p><p><strong>Rapid Compilation &amp; Hot Module Replacement</strong></p><p>Employing native ES modules and modern browser APIs, Vite compiles your code instantly, offering swift build times and immediate updates in the browser. This method sidesteps the need for traditional bundlers in development, slashing the time you spend on building and deploying your apps. Vite’s built-in development server is fine-tuned for speedy reloads and HMR, enabling you to witness code changes in real-time without refreshing the entire page.</p><p><strong>Efficient Lazy Loading</strong></p><p>Vite champions lazy-loading, ensuring code is only fetched when necessary. This not only shrinks bundle sizes but also elevates performance, particularly for hefty applications. Lazy loading enhances initial load times for your audience, as it defers loading for non-essential parts of your app until they’re needed.</p><p><strong>Optimization via Tree-shaking &amp; Code Splitting</strong></p><p>With optimization strategies like tree-shaking and code splitting, Vite trims your code’s size and boosts performance. Tree-shaking eradicates unused code, and code splitting breaks down your code into smaller, manageable pieces that load as needed. These tactics guarantee that users download only what’s necessary for the current page, speeding up load times and enhancing performance.</p><h3>Kickstarting with Vite 🌟</h3><p>Setting up a Vite project is straightforward. If you’re working with React, for example, you can create a new project by running:</p><pre>npm create vite@latest my-vite-app</pre><h3>Drawbacks of Vite 😕</h3><p><strong>Nascent Community</strong></p><p>Being a newcomer in the frontend tool arena, Vite’s community is smaller compared to veterans like Create React App or Webpack. This could make seeking support or troubleshooting more challenging.</p><p><strong>Restricted Browser Compatibility</strong></p><p>Vite leans on modern JavaScript features not universally supported across browsers. Consequently, some users might face accessibility hurdles without browser updates or polyfills.</p><h3>How Does Vite Enhance Your Development Workflow?</h3><p>Imagine you’re working on a large React project. Each component update traditionally requires the browser to process the entire bundle, leading to slower feedback loops. With Vite, only the changed module is recompiled and updated in the browser. This means you can see your changes almost instantly, dramatically improving your development speed.</p><p>Moreover, Vite’s development server serves files over native ESM, an approach that is both faster and more efficient than traditional bundling during development. This method also eliminates the need for source map overhead, making debugging quicker and more straightforward.</p><h3>Conclusion ✨</h3><p>Vite stands out as a formidable advancement in frontend development tools, delivering unmatched speed, efficiency, and an enhanced developer experience. Whether your projects involve React, Vue, Angular, or vanilla JavaScript, Vite’s simplicity and performance improvements render it an essential asset in your development arsenal. Dive deeper into Vite by exploring the <a href="https://vitejs.dev/guide/">official Vite documentation</a>.</p><p><em>Originally published at </em><a href="https://10xdev.codeparrot.ai/what-is-vite"><em>https://10xdev.codeparrot.ai</em></a><em> on February 28, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eeba6e284af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Side Rendering with Next.js]]></title>
            <link>https://medium.com/codeparrot-ai/server-side-rendering-with-next-js-e8ff3b996ee6?source=rss-cfecf0654b7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ff3b996ee6</guid>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Royal Jain]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 11:23:25 GMT</pubDate>
            <atom:updated>2024-01-15T11:23:25.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Server-Side Rendering with Next.js" src="https://cdn-images-1.medium.com/proxy/0*zSS56Q2InvHTHnrB" /></figure><p>CodeParrot is a developer first design to code tool. It uses AI to convert components from Figma files to production-ready code. For 10x faster Design to Code using AI, <a href="https://www.codeparrot.ai/?md">Try CodeParrot AI</a></p><p>Next.js, a powerful framework for React, has emerged as a game-changer, especially in the world of SSR. This blog post explores the differences between client-side and server-side rendering, Server-Side Rendering with Next.js, and its pros and cons.</p><h4>Understanding Client-Side vs. Server-Side Rendering</h4><p>Before jumping into Next.js, it’s crucial to understand the differences between CSR and SSR.</p><h4>Client-Side Rendering (CSR)</h4><p><strong>How it Works</strong>: In CSR, the browser downloads a minimal HTML page, JavaScript, and CSS. The JavaScript then renders the content on the browser.</p><p><strong>Pros</strong>: Rich user interactions, reduced server load, and dynamic content updates.</p><p><strong>Cons</strong>: Slower initial page loads, potential SEO challenges</p><h4>Server-Side Rendering (SSR)</h4><p><strong>How it Works</strong>: With SSR, the server sends a fully rendered HTML page to the browser.</p><p><strong>Pros</strong>: Faster initial page load, improved SEO, and consistent rendering across different devices.</p><p><strong>Cons</strong>: Higher server load, potentially less interactive, and can be more complex to implement.</p><h4>Server-Side Rendering with Next.js</h4><p>Next.js combines the best of both worlds, allowing developers to use server-side rendering for initial page loads and client-side rendering for subsequent navigations. Setting Up a Next.js Project</p><ol><li>Install Node.js: Ensure you have Node.js installed on your system.</li><li>Create a Next.js App: Use the create-next-app command to set up a new project</li></ol><pre>npx create-next-app@latest my-next-app</pre><ol><li>Run Your Next.js App: Navigate to your project folder and start the development server:</li></ol><pre>cd my-next-app<br>npm run dev</pre><ol><li>Open the App: Open your browser and go to <a href="http://localhost:3000/">http://localhost:3000</a></li></ol><h4>Pros and Cons of Using Next.js for SSR</h4><h4>Pros</h4><p><strong>Optimized Performance</strong>: Next.js optimizes your application for better performance.</p><p><strong>SEO Friendly</strong>: Enhanced SEO thanks to server-side rendering.</p><p><strong>Easy to Get Started</strong>: Simple setup and automatic routing make it beginner-friendly.</p><p><strong>Hybrid Rendering</strong>: Choose between SSR, CSR, or static generation as per your page’s needs.</p><h4>Cons</h4><p><strong>Learning Curve</strong>: Requires understanding Next.js conventions on top of React knowledge.</p><p><strong>Server-Side Complexity</strong>: Managing server-side logic can be complex, especially for larger applications.</p><p><strong>Resource Intensive</strong>: SSR can be more demanding on server resources than client-side rendering alone.</p><h4>Conclusion</h4><p>Next.js offers a robust solution for developers looking to leverage server-side rendering in their React applications. Its ability to combine SSR with CSR and static generation provides flexibility and performance benefits that are hard to match.</p><h4>Further Reading</h4><p><a href="https://nextjs.org/learn">Learn Next.js | Next.js by Vercel - The React Framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ff3b996ee6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeparrot-ai/server-side-rendering-with-next-js-e8ff3b996ee6">Server-Side Rendering with Next.js</a> was originally published in <a href="https://medium.com/codeparrot-ai">CodeParrot.ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>