<?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 Gunjan Kalita on Medium]]></title>
        <description><![CDATA[Stories by Gunjan Kalita on Medium]]></description>
        <link>https://medium.com/@eklavya_?source=rss-b9e36b4d676e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*_287UcMAZx-xJcUEOBz7Dw.jpeg</url>
            <title>Stories by Gunjan Kalita on Medium</title>
            <link>https://medium.com/@eklavya_?source=rss-b9e36b4d676e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:06:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eklavya_/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[The Ultimate Production Readiness Checklist for Your Express App]]></title>
            <link>https://medium.com/@eklavya_/the-ultimate-production-readiness-checklist-for-your-express-app-c3b1e2dd2555?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b1e2dd2555</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 06:13:25 GMT</pubDate>
            <atom:updated>2024-12-23T06:13:25.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HgZ2W8jaDgExIoEVblr2w.jpeg" /><figcaption>Photo by 子刚 chen</figcaption></figure><h4><strong>Effective Error Handling in Express Applications</strong></h4><p>Error handling is a critical aspect of any service, whether it’s the frontend or the backend. It’s essential to define a consistent and clear error-handling strategy across your application to ensure that errors are communicated correctly to the client.</p><p>One approach I use extensively in Express applications involves centralizing error management to streamline the process and enhance maintainability. Below are some key highlights of this design:</p><ol><li><strong>Avoid Overusing </strong><strong>try-catch Blocks</strong>:<br>Instead of scattering try-catch blocks throughout your code, it’s more efficient to centralize error handling in one place. This way, you can manage errors consistently across the entire application.</li><li><strong>Leverage Error Middleware in Express</strong>:<br>Use Express’s built-in error-handling middleware to catch and respond to errors. This approach ensures that errors are sent to the client in a standardized manner, without the need for each controller to handle errors individually.</li><li><strong>Define Errors Clearly</strong>:<br>It’s crucial to define your error types and messages explicitly to ensure clarity and consistency. In the following sections, I’ll provide examples to demonstrate how to structure your errors for better readability and maintainability.</li></ol><p>By centralizing error handling and defining clear error structures, you can ensure that your application remains robust, maintainable, and user-friendly.</p><p>Let’s learn more on this one by one.</p><h4><strong>Avoid Overusing </strong><strong>try-catch Blocks:</strong></h4><pre>// ❌ General use, let&#39;s not do this<br>const createUser = async (req, res) =&gt; {<br>    try {<br>        // Implement the controller<br>    } catch(e) {    <br>        // handle errors<br>    }<br>}<br><br>// ✅ Use this instead. <br><br>const catchAsync = (fn) =&gt; {<br>  return function (req, res, next) {<br>    Promise.resolve(fn(req, res, next)).catch((err) =&gt; next(err));<br>  };<br>};<br><br>const createUser = catchAsync(async (req, res) =&gt; {<br>       // Implement the controller<br>});<br><br>const loginUser = catchAsync(async (req, res) =&gt; {<br>       // Implement the controller<br>});</pre><p>You can clearly notice the reusability of this code. More benefits on this on going ahead.</p><h4><strong>Leverage Error Middleware in Express</strong>:</h4><p>In the catchAsync function, you can observe that we are calling next(err). This is a mechanism for passing the error to a special error-handling middleware in Express. By leveraging this middleware, we can centralize the process of handling errors and send a consistent, structured response to the client. Eg,</p><pre>const errorHandler = (err, req, res, next) =&gt; {<br>  const { message } = err;<br>  res.status(/* STATUS_CODE */).send({ message });<br>};<br><br>// Add this to the express App. <br>app.use(errorHandler);</pre><h4><strong>Define Errors Clearly</strong></h4><p>This is probably the most important part of this topic. The idea is that we have to declare errors and the corresponding messages explecetly. Let me give you a code example to demonstrate this.</p><pre>class ApiError extends Error {<br>   <br>  constructor(message, stackTrace) {<br>    super(message)<br>    this.stackTrace = stackTrace<br>    this.message = message<br>  }<br><br>  transform () {<br>    const message = {<br>      stack: process.env.NODE_ENV === &#39;prod&#39; ? this.stackTrace : null,<br>      message: {}  // do the transform here <br>    }<br>    // do your transform here. <br>    return message<br>  }<br>}<br><br>const STATUS_CODES = {<br>  NOT_FOUND: 404,<br>  INTERNAL_SERVER_ERROR: 500,<br>  UNAUTHORISD: 401<br>} <br><br>// Define Not Found errors<br>class NotFoundError extends ApiError {<br>  STATUS_CODE = STATUS_CODES.NOT_FOUND<br>  constructor(message) {<br>    super(message)<br>  }<br><br>  send() {<br>    return {<br>      code: STATUS_CODE,<br>      message: this.transform()<br>    }<br>  }<br>}<br><br>// Define Internal server errors<br>class InternalServerError extends ApiError {<br>  STATUS_CODE = STATUS_CODES.INTERNAL_SERVER_ERROR<br>  constructor(message) {<br>    super(message)<br>  }<br><br>  send() {<br>    return {<br>      code: STATUS_CODE,<br>      message: this.transform()<br>    }<br>  }<br>}</pre><p>And call these errors from these controllers</p><pre>const createUser = catchAsync(async (req, res) =&gt; {<br>       if (internalError) {<br>           throw new InternalServerError()<br>       }<br>});<br><br>const loginUser = catchAsync(async (req, res) =&gt; {<br>       if (notFoundError) {<br>           throw new NotFoundError()<br>       }<br>});</pre><h4>Handle Terminate/Interrupt Signals</h4><p>In Node.js, you can handle <strong>Terminate</strong> and <strong>Interrupt</strong> signals (such as SIGINT and SIGTERM) by using the process object. These signals are typically sent by the operating system to request that the process terminates or be interrupted (e.g., when the user presses Ctrl+C in the terminal, or when the process is killed).</p><p>To gracefully handle termination or interruption of your Node.js application, you can listen for these signals and perform necessary cleanup operations before the process is killed.</p><pre>// Function to clean up resources<br>function cleanup() {<br>  console.log(&#39;Cleaning up resources...&#39;);<br><br>  // Example: Close database connections, sockets, stop background tasks, etc.<br><br>   console.log(&#39;Cleanup done, process exiting...&#39;);<br>  process.exit(0); //Then Exit the process cleanly with status code 0<br>  }<br><br>// Handle SIGINT (Ctrl+C)<br>process.on(&#39;SIGINT&#39;, () =&gt; {<br>  console.log(&#39;Received SIGINT (Ctrl+C), terminating gracefully...&#39;);<br>  cleanup();<br>});<br><br>// Handle SIGTERM (Termination Signal)<br>process.on(&#39;SIGTERM&#39;, () =&gt; {<br>  console.log(&#39;Received SIGTERM, terminating gracefully...&#39;);<br>  cleanup();<br>});<br><br>// Handle unhandled promise rejections and uncaught exceptions<br>process.on(&#39;unhandledRejection&#39;, (reason, promise) =&gt; {<br>  console.error(&#39;Unhandled Rejection at:&#39;, promise, &#39;reason:&#39;, reason);<br>  cleanup();<br>});<br><br>process.on(&#39;uncaughtException&#39;, (err) =&gt; {<br>  console.error(&#39;Uncaught Exception:&#39;, err);<br>  cleanup();<br>});</pre><h4>Adding Testing infra to your code</h4><p>Establish a robust unit and integration test setup to ensure comprehensive verification of every functionality you develop. Leverage powerful testing tools like <strong>Jest</strong> for unit testing and <strong>Supertest</strong> for integration testing to thoroughly test both individual components and the interaction between different parts of the application. This approach will help you catch issues early, improve code reliability, and maintain high-quality standards throughout development.</p><pre>test(&#39;Verify functionality xyz in the api&#39;, async () =&gt; {<br>  const res = await request(app).post(&quot;/v1/xyz&quot;).send({<br>    id: &quot;abc&quot;,<br>    data: {<br><br>    }<br>  }) // request wants an express app to call. <br>  expect(res.status).tobeDefined()<br>  // test further  <br>})</pre><h4>Use PM2 to run the server</h4><p><strong>PM2</strong> is a popular process manager for Node.js applications, particularly useful for managing and running <strong>Express</strong> applications in production. It helps ensure that your Express app runs smoothly by providing features like automatic restarts, load balancing, and log management. PM2 makes it easy to deploy applications in a production environment, handle process crashes, and manage multiple instances of your Express app. It also provides useful monitoring tools and can be configured to restart your app on system reboots, improving uptime and reliability. With PM2, you can easily manage the performance and lifecycle of your Express app, ensuring it runs efficiently even under heavy traffic.</p><p>How to use ?</p><pre>// instead of <br>&quot;dev&quot;: &quot;node src/app.js&quot;,<br><br>// do <br>&quot;dev&quot;: &quot;pm2 start src/app.js&quot;<br><br>// to monitor run in terminal<br>pm2 monit </pre><h4>Routes Implementation:</h4><p>Routers are very powerful in Express and they can be used very efficiently to write clean and version specific code to address various crucial mantainance and development needs. Here if an example of this.</p><pre>// ❌ Avoid doing this <br><br>router.get(&#39;/v1/api/xyz&#39;, (req, res) =&gt; {})<br>router.get(&#39;/v1/api/abc&#39;, (req, res) =&gt; {})<br><br>// ✅ Do this <br>const router = Express.Router()<br>router.get(&#39;/xyz&#39;, (req, res) =&gt; {})<br>router.get(&#39;/abc&#39;, (req, res) =&gt; {})<br><br>// create V1 Router <br>const v1Router = Express.Router()<br>v1Router.use(&quot;/v1/api&quot;, router)<br><br>// If needed create further versions<br></pre><h4>Halmet and rate limters</h4><p><strong>Helmet.js</strong> is a middleware for Express that helps secure your application by setting various HTTP headers. These headers improve the security posture of your app by preventing certain types of attacks like <strong>XSS</strong>, <strong>clickjacking</strong>, and <strong>content sniffing</strong>.</p><pre>// Use this in your express app as a plugin<br>app.use(helmet());</pre><p>Rate limiting is used to limit the number of requests that can be made to your server within a certain time frame. This helps prevent <strong>Denial of Service (DoS)</strong> attacks, <strong>brute force</strong> login attempts, and reduces the risk of other abusive behaviors.</p><pre>// Set up rate limiter: Limit to 100 requests per 15 minutes from a single IP<br>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,  // 15 minutes<br>  max: 100,  // Limit each IP to 100 requests per windowMs<br>  message: &#39;Too many requests from this IP, please try again later.&#39;,<br>  standardHeaders: true,  // Return rate limit info in the `RateLimit-*` headers<br>  legacyHeaders: false,   // Disable the `X-RateLimit-*` headers<br>});<br><br>// Apply the rate limiter to all routes<br>app.use(limiter);</pre><h4>logging and performance matrix</h4><p>Use Winston to add better logging to your express application.</p><pre>const winston = require(&#39;winston&#39;);<br>const morgan = require(&#39;morgan&#39;);<br><br>const app = express();<br><br>// Create a custom logger using Winston<br>const logger = winston.createLogger({<br>  level: &#39;info&#39;, // Log level (info, warn, error)<br>  format: winston.format.combine(<br>    winston.format.timestamp(),<br>    winston.format.json() // Log in JSON format<br>  ),<br>  transports: [<br>    new winston.transports.Console(), // Log to the console<br>    new winston.transports.File({ filename: &#39;logs/app.log&#39; }) // Log to a file<br>  ]<br>});<br><br>// Use Morgan to log HTTP requests and integrate with Winston<br>app.use(morgan(&#39;combined&#39;, { stream: { write: (message) =&gt; logger.info(message.trim()) }}));<br><br>// Sample route<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  logger.info(&#39;Request received at root route&#39;);<br>  res.send(&#39;Hello World&#39;);<br>});</pre><h4>Docker setup:</h4><p>containerize your application to ship to prod with confidence. No set up issues, no env issues what so ever.</p><p>Add a .dockerfile to do so.</p><pre>FROM node: alpine     # base image <br><br>WORKDIR /app          # use app directory going ahead<br><br>COPY package.json .   # copy the file to docker env<br><br>RUN npm install       # install everything<br><br>COPY . .              # copy rest of your code<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]  # Run npm start</pre><p>Thanks :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b1e2dd2555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Starter Kit for Building and Publishing React Component Libraries]]></title>
            <link>https://medium.com/@eklavya_/complete-starter-kit-for-building-and-publishing-react-component-libraries-7d81ab04806a?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d81ab04806a</guid>
            <category><![CDATA[development-libraries]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[starter]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 09:41:11 GMT</pubDate>
            <atom:updated>2024-12-20T09:41:11.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRUNbhnSXWB7AoP95eyLaQ.jpeg" /><figcaption>Photo by Markus Spiske</figcaption></figure><p>Building reusable React components and sharing them with the world has become an essential skill for modern developers. Whether you’re contributing to the open-source ecosystem or creating internal libraries for your team, publishing React components to <strong>npm</strong> is a streamlined way to distribute your work. However, the process of setting up a library that’s both easy to develop and share can often feel daunting.</p><p>In this blog, we introduce a <strong>React library template</strong> that simplifies the entire process. This template not only provides a solid foundation for publishing React components to npm but also comes bundled with a <strong>Vite-powered React app</strong> for seamless development and testing. It’s designed to be flexible: whether you’re building a complex UI library, a single reusable component, or just experimenting with React, this template is your go-to solution.</p><p>Here’s why this template stands out:</p><ul><li><strong>Effortless Publishing</strong>: Preconfigured for npm, so you can focus on your code instead of battling configurations.</li><li><strong>Integrated Development Environment</strong>: The Vite-powered React app is perfect for live development, testing, and showcasing your components.</li><li><strong>Versatile Usage</strong>: Developers can use it as-is for their library or adapt it to their unique needs with minimal effort.</li></ul><p>If you’ve ever wanted to simplify the process of building and sharing React components, or you’re looking for a boilerplate to kickstart your library development, this blog is for you. Let’s dive in and see how you can make your React components shareable, reusable, and easy to develop — all in one package!</p><h4>Step1: Create a simple React component in Js and publish:</h4><p>To get started, first, set up a barebones Node.js project by running the following command in your terminal:</p><pre>npm init -y</pre><p>This will create a basic package.json file for your project.</p><p>Next, install the required packages by running the command below:</p><pre>npm install --save-dev @babel/core @babel/cli @babel/preset-react @babel/preset-env</pre><p>After this create a .babelrc file and add the below config to it.</p><pre>{<br>    &quot;presets&quot;: [&quot;@babel/preset-react&quot;, &quot;@babel/preset-env&quot;]<br>}</pre><p>Then create the folder structure below.</p><pre>my-react-component/<br>├── src/<br>│   └── MyComponent.jsx<br>|.  └── index.js <br>├── dist/<br>├── .babelrc<br>├── package.json</pre><p>Inside MyComponent.jsx<strong> </strong>we will create the react component we want to publish to npm. In this case we will have a very simple component for demo purposes. Use this if you are following along.</p><pre>// MyComponent/MyComponent.jsx<br>import React from &#39;react&#39;;<br><br>const MyComponent = ({ text }) =&gt; {<br>  return &lt;div&gt;{text}&lt;/div&gt;;<br>};<br><br>export default MyComponent;</pre><p>&amp; inside index.js</p><pre>// index.js<br>import MyComponent from &#39;./MyComponent&#39;;<br><br>export default MyComponent;</pre><p>Great! Now before we publish, there are few things we need to take care of.</p><ol><li>We cannot publish this project as it is. This is because React components are written in Jsx and we need to transpile it to Js before we push it to npm.</li><li>We must specify npm what is the entry point of our project which currently not specified in our app.</li><li>Also, there are lot of things in the project till now which we do not want to push to npm. For example, the node_modules/ folder.</li></ol><p>Let’s solve all of these one by one.</p><p><strong>Resolution for issue 1: <br></strong>To convert our component to Js, we need to update our package.json with the following script.</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;babel src --extensions &#39;.js,.jsx&#39; --out-dir dist&quot;,<br>  }<br>}</pre><p>This configuration instructs Babel to transpile the src directory into a new directory called dist, while processing both .js and .jsx files.</p><p>Now, run npm run build to create a build of your React component. This will populate the dist directory with the transpiled files, and the structure will look like this:</p><pre>my-react-component/<br>├── src/<br>│   └── MyComponent.jsx<br>|.  └── index.js <br>├── dist/<br>|   └── MyComponent.js<br>|.  └── index.js<br>├── .babelrc<br>├── package.json</pre><p><strong>Resolution for issue 2: <br></strong>Now that we have our build ready to push to npm, there’s one more thing to address: our project doesn’t yet know the entry point of the application. To resolve this, we need to update the package.json file with the following configurations:</p><pre>{<br>  &quot;name&quot;: &quot;my-reaact-component&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,  // Add this <br>  &quot;module&quot;: &quot;dist/index.js&quot;, // &amp; Add this<br>  &quot;scripts&quot;: {<br>      &quot;build&quot;: &quot;babel src --extensions &#39;.js,.jsx&#39; --out-dir dist&quot;,<br>    },<br>    &quot;author&quot;: &quot;&quot;,<br>    &quot;license&quot;: &quot;ISC&quot;,<br>    &quot;devDependencies&quot;: {<br>      &quot;@babel/cli&quot;: &quot;^7.26.4&quot;,<br>      &quot;@babel/preset-env&quot;: &quot;^7.26.0&quot;,<br>      &quot;@babel/preset-react&quot;: &quot;^7.26.3&quot;<br>    },<br>}</pre><p>If you’re unsure, I’ve added two flags: main and module to the package.json. Both are necessary because main will be used by CommonJS applications, while module will be used by modern apps built with ES Modules. Since this is a library, it&#39;s important to account for both configurations.</p><p><strong>Resolution for issue 3:</strong></p><p>Lastly, our project contains directories like node_modules, src, and configuration files such as .babelrc, which we don’t want to push to npm. To ensure these files remain excluded, let&#39;s add a .npmignore file and specify what should stay invisible to npm.</p><pre>// Inside .npmIgnore <br>node_modules/<br>src/<br>*.log<br>.babelrc</pre><p>And we are sorted! The task next in hand is to publish it for the first time. For that fire the command bellow in a sequence.</p><pre>npm login<br>npm publish --access public</pre><p>And that’s it. You will have your component hosted for the first time at npm js. Please do confirm from the terminal and from the npmjs console as well.</p><p><strong>Beautified Version:</strong></p><p>If you’ve followed along so far, cheers to your efforts! 🎉 However, this is just half the journey. There are still several crucial components we need to add, such as:</p><ul><li><strong>Handling updates to your library</strong></li><li><strong>TypeScript compatibility</strong></li><li><strong>Seamless development setup</strong></li><li><strong>Linting and testing</strong> to maintain code quality</li><li><strong>Pre-commit hooks</strong> to automate checks and improve workflow</li></ul><p>I know this might sound daunting, but don’t worry — I’ll guide you step by step to incorporate all of these into your project.</p><p>It’s important to note that none of these are strictly required to publish your component. However, these are widely regarded as <strong>industry standards</strong>, and if you’re serious about building a professional-grade library, they’re worth the effort. So, let’s take this challenge head-on and create something robust and ready for the real world! 💪</p><h4><strong>Handling updates to your library</strong></h4><p>Up until now, we’ve successfully published our library to npm. But what if we need to update our library and re-publish the changes? Fortunately, this is a simple process. Just make the necessary changes, then update the package.json with the following instructions.</p><pre>&quot;version&quot;: &quot;1.0.1&quot; // earlier 1.0.0, just update it to a newer one.</pre><p>Then run npm publish to push the changes. That’s it :)</p><p><strong>TypeScript compatibility</strong></p><p>TypeScript is an essential feature for any modern library. However, to integrate it, we need to do some heavy lifting. First, remove all the Babel-related dependencies from your project and replace them with TypeScript dependencies. Why? Because TypeScript can directly compile .tsx files into .js without the need for a separate transpiler—it&#39;s essentially a &quot;2-in-1&quot; solution.</p><p>So, add…</p><pre>npm install --save-dev typescript react react-dom @types/react @types/react-dom</pre><p>Update the component to have typescript definitions. (like this)</p><pre>// src/MyComponent.tsx<br>import React from &#39;react&#39;;<br><br>interface MyComponentProps {<br>  text: string;<br>}<br><br>const MyComponent: React.FC&lt;MyComponentProps&gt; = ({ text }) =&gt; {<br>  return &lt;div&gt;{text}&lt;/div&gt;;<br>};<br><br>export default MyComponent;</pre><p>In index.ts</p><pre>// src/index.ts<br>export { default as MyComponent } from &#39;./MyComponent&#39;;</pre><p>Next, add a tsconfig.json file and add the following components. Please note, configs added here is very straight forward and you should understand this just by looking at it.</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>      &quot;target&quot;: &quot;ES6&quot;,                           // JavaScript version to compile to<br>      &quot;module&quot;: &quot;ESNext&quot;,                        // Use ES modules<br>      &quot;jsx&quot;: &quot;react-jsx&quot;,                        // React JSX syntax<br>      &quot;declaration&quot;: true,                       // Generate .d.ts files for type definitions<br>      &quot;declarationDir&quot;: &quot;dist&quot;,                  // Output directory for type definitions<br>      &quot;outDir&quot;: &quot;dist&quot;,                          // Output directory for compiled files<br>      &quot;strict&quot;: true,                            // Enable strict type checking<br>      &quot;esModuleInterop&quot;: true,                   // Allow default imports from CommonJS modules<br>      &quot;skipLibCheck&quot;: true,                      // Skip checking types of imported libraries<br>      &quot;moduleResolution&quot;: &quot;node&quot;,               // Resolve modules like Node.js<br>      &quot;allowSyntheticDefaultImports&quot;: true      // Allow default imports for CommonJS modules<br>    },<br>    &quot;include&quot;: [&quot;src&quot;],                          // Include files to compile<br>    &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;]          // Exclude unnecessary files<br>  }  </pre><p>And then, update your package.json to have a new build command…</p><pre>&quot;build&quot;: &quot;tsc&quot;</pre><p>Now create your build by hitting npm run build again ! Your project will now look like this.</p><pre>my-react-component/<br>├── src/<br>│   └── MyComponent.jsx<br>|.  └── index.js <br>├── dist/<br>|   └── index.d.ts <br>|.  └── index.js<br>|.  └── MyComponent.d.ts<br>|.  └── MyComponent.js<br>├── .babelrc<br>├── package.json</pre><p>Well done! Finally update your package.json to identify the type definitions available in your project.</p><pre>{<br>  &quot;name&quot;: &quot;my-react-component&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/index.js&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;, // &lt;- this identifies the types in our project. </pre><p>Now follow the steps to re-publish and you are not having a typescript compatible library.</p><h4><strong>Creating a Seamless development setup</strong></h4><p>Imagine having a development setup seamlessly integrated into your project, allowing you to see your component in a live app in real-time. That’s exactly what we’re doing in this project, and the best part is, the steps are surprisingly simple!</p><p>To do this, create a react app in a new folder eg client . You can use vite or cra, that’s upto you. Inside your project, just fire the command..</p><pre>npm install ../</pre><p>And that’s it! 🎉 You can start using your component in your React app right from your local setup. However, there’s a small pitfall you should be aware of. If you try to update your library and refresh your React app, <strong>it won’t work!</strong> 😬</p><p>Why, you ask? Well, the issue lies in the fact that your package is exporting the component from the dist folder, not from src. So, when you make changes, they don’t automatically reflect in the dist folder. Let’s fix that and get everything working smoothly. 💡</p><p>To solve this, add this in package.json in root level.</p><pre>&quot;watch&quot;: &quot;tsc --watch&quot;,<br>&quot;dev&quot;: &quot;concurrently \&quot;npm run watch\&quot; \&quot;cd client3 &amp;&amp; npm run start\&quot;&quot;</pre><p>Now, to steamline development, run npm run dev and you will the changes in your library reflected in your app without any hussle.</p><h4><strong>Adding testing infra:</strong></h4><p>Adding a testing infrastructure to a project like this can be challenging, but don’t worry! Let’s break down the essential components for this setup.</p><p>You’ll need the following libraries:</p><ol><li><strong>Jest</strong>: A JavaScript test runner to execute tests.</li><li><strong>React Testing Library &amp; user-events</strong>: For testing React components and simulating user interactions.</li><li><strong>Jest-DOM</strong>: Provides DOM-specific matchers to supplement Jest for easier assertions.</li><li><strong>ts-jest</strong>: A Jest preprocessor that enables Jest to understand TypeScript files.</li><li><strong>jest-environment-jsdom</strong>: Simulates a browser-like environment for testing.</li></ol><p>Now, let’s install all of these dependencies with a single command:</p><pre>npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event jest ts-jest @types/jest jest-environment-jsdom</pre><p>Then add the bellow 2 config files</p><p>jest.config.ts</p><pre>/** @type {import(&#39;jest&#39;).Config} */<br>import { pathsToModuleNameMapper } from &quot;ts-jest&quot;;<br>import { compilerOptions } from &quot;./tsconfig.json&quot;;<br><br><br>module.exports = {<br>  preset: &quot;ts-jest&quot;, <br>  testEnvironment: &quot;jest-environment-jsdom&quot;,<br>  transform: {<br>    &quot;^.+\\.tsx?$&quot;: &quot;ts-jest&quot;,<br>  },<br>  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: &quot;&lt;rootDir&gt;/&quot; }),<br>  setupFilesAfterEnv: [&#39;&lt;rootDir&gt;/setupTests.ts&#39;],<br>};</pre><p>setupTest.ts</p><pre>import &#39;@testing-library/jest-dom&#39;;</pre><p>Then, start adding the test scripts. Eg</p><p>MyComponent.test.tsx in src folder</p><pre>import { render, screen, fireEvent } from &#39;@testing-library/react&#39;;<br>import MyComponent from &quot;./MyComponent&quot;;<br><br>test(&#39;renders a button with the given label&#39;, () =&gt; {<br>  render(&lt;MyComponent text=&quot;Click Me&quot; /&gt;); // Render the component<br>});</pre><p>And hit npm test to run test commands.</p><h4>Add Listing &amp; Husky support:</h4><p>Linting support is crucial for maintaining consistent code quality throughout your project. Let’s quickly set it up in our project to ensure we adhere to best practices and catch potential issues early.</p><p>Please install</p><pre>npm install --save-dev eslint eslint-config-airbnb eslint-plugin-react eslint-plugin-import eslint-plugin-jsx-a11y</pre><p>Add Husky</p><pre>npm install husky@8 --save-dev</pre><p>Firstly we will setup lint and then ask husky to run then before commit. For that create .eslintrc.js and add the configs bellow</p><pre>module.exports = {<br>    env: {<br>      node: true, // Node.js environment<br>      browser: true, // Browser environment (if needed)<br>    },<br>    parser: &#39;@typescript-eslint/parser&#39;,<br>    parserOptions: {<br>      ecmaVersion: 2020,<br>      sourceType: &#39;module&#39;, // Allow imports<br>    },<br>    extends: [<br>      &#39;eslint:recommended&#39;,<br>      &#39;plugin:react/recommended&#39;,<br>      &#39;plugin:@typescript-eslint/recommended&#39;,<br>    ],<br>    plugins: [&#39;react&#39;, &#39;@typescript-eslint&#39;],<br>    settings: {<br>      react: {<br>        version: &#39;19.0.0&#39;, // Automatically detect the version of React<br>      },<br>    },<br>    rules: {<br>      // You can specify additional rules here if needed<br>    },<br>  };</pre><p>Run the command npx eslint . to verify if linting is working.</p><p>After that add lint-staged instructions in package.json file so that husky can run them.</p><pre> &quot;lint-staged&quot;: {<br>    &quot;*.ts&quot;: &quot;eslint --fix&quot;,<br>    &quot;*.tsx&quot;: &quot;eslint --fix&quot;,<br>    &quot;*.js&quot;: &quot;eslint --fix&quot;,<br>    &quot;*.jsx&quot;: &quot;eslint --fix&quot;<br>  }</pre><p>Run</p><pre>npx husky install<br>npx husky add .husky/pre-commit &quot;npx lint-staged&quot;</pre><p>The command above will set up lint-staged instructions from package.json to be triggered by Husky during the pre-commit phase. To verify the setup, check if the pre-commit file exists in the .husky folder and ensure it matches the example below.</p><pre>#!/bin/sh<br>. &quot;$(dirname &quot;$0&quot;)/_/husky.sh&quot;<br><br>npx lint-staged</pre><p>Now, you have a library that pushes React components to npm, with an integrated environment for development, testing support, linting, and pre-commit hooks. Finally, update the .npmignore file to exclude unwanted setups from being published to npm. It should look like this:</p><pre>node_modules/<br>src/<br>*.log<br>.babelrc<br>client/<br>.husky<br>.eslintrc.js<br>.jest.config.js<br>setupTests.ts<br>tsconfig.json</pre><p>I cannot wait to see what you build with this :)</p><p>If you’re simply interested in developing the library right away, feel free to fork the GitHub repo below and use it as starter code.</p><p><a href="https://github.com/Gaurav2048/react-lib-starter-code">GitHub - Gaurav2048/react-lib-starter-code</a></p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d81ab04806a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three solid ways to achieve Abstraction in React]]></title>
            <link>https://medium.com/@eklavya_/three-solid-ways-to-achieve-abstraction-in-react-8b00b2ab8542?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b00b2ab8542</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 15:26:43 GMT</pubDate>
            <atom:updated>2024-09-07T15:26:43.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2I1QiwmfU9F4mK30G2N8A.jpeg" /></figure><p>In React development, mastering the art of abstraction can take your code from functional to elegant. Abstraction isn’t just a buzzword — it’s a powerful technique that simplifies complex logic, makes your components reusable, and keeps your codebase clean and scalable. Whether you’re just starting with React or looking to level up your skills, understanding how to effectively abstract your code can dramatically improve your workflow. In this blog, we’ll explore three solid ways to achieve abstraction in React, helping you build applications that are both easier to maintain and more efficient. <br><br><strong>**What Abstraction Does for Us in Code**</strong></p><p>Abstraction in code serves a vital role, particularly when working with component-based libraries like React. At its core, abstraction is about hiding the complex inner workings of a component while exposing only the essential parts that other developers or even your future self need to interact with. By doing so, you simplify the way the component is used, offering a clean and intuitive interface. This becomes incredibly important when building reusable components for a library, where the end goal is to make them as user-friendly and adaptable as possible.</p><p>Imagine a component with layers of intricate logic — conditional rendering, state management, and side effects. Without abstraction, every developer who touches the component would need to wade through this complexity to understand and use it. By abstracting these details away, you shield the user from the internal chaos, allowing them to interact with the component using simple, clear props or APIs. The result? Code that’s not only easier to work with but also more maintainable and less prone to errors.</p><p>In a React context, abstraction enables you to create flexible, reusable components that can be dropped into any project with minimal configuration. It turns complicated features into simple, powerful tools that anyone can use, regardless of their familiarity with the underlying logic. Let’s dive in.</p><p><strong>Method 1: Higher order components (HOC)</strong></p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>// Higher-Order Component<br>const withLoading = (WrappedComponent) =&gt; {<br>  return function LoadingComponent({ ...props }) {<br>    const [ loading, setLoading ] = useState(false)<br>    const [ data, setData ] = useState()<br><br>    const fetchData = async () =&gt; {<br>      setLoading(true)<br>      try {<br>        const res = await (await fetch(/** some url */)).json()<br>        setData(res)<br>      } catch (e) {<br><br>      } finally {<br>        setLoading(false)<br>      }<br>    }<br><br>    useEffect(() =&gt; {<br>      fetchData()<br>    }, [])<br>    <br>    if (loading) {<br>      return &lt;div&gt;Loading...&lt;/div&gt;;<br>    }<br>    return &lt;WrappedComponent data={data} /&gt;;<br>  };<br>};<br><br>// Simple functional component<br>const DataDisplay = ({ data }) =&gt; {<br>  return &lt;div&gt;Data: {data}&lt;/div&gt;;<br>};<br><br>// Wrapping DataDisplay component with HOC<br>const DataDisplayWithLoading = withLoading(DataDisplay);<br><br>// Example usage<br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Higher-Order Component Example&lt;/h1&gt;<br>      &lt;DataDisplayWithLoading  /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>This code demonstrates a <strong>**Higher-Order Component (HOC)** </strong>in React called `withLoading`. The `withLoading` HOC takes a component (`WrappedComponent`) as an argument and returns a new component that adds data fetching and loading functionality.</p><p>Inside the HOC:<br>- <strong>**State management**</strong> is handled by two `useState` hooks: `loading` (to track the loading state) and `data` (to store fetched data).<br>- The `fetchData` function asynchronously fetches data from an API. During the process, it sets `loading` to `true`, fetches data, and updates the `data` state, then toggles `loading` to `false`.<br>- The `useEffect` hook ensures the `fetchData` function runs only once when the component mounts.</p><p>If `loading` is `true`, it renders a “Loading…” message. Once the data is fetched, it renders the `WrappedComponent`, passing the data as a prop. In this example, `DataDisplayWithLoading` is the enhanced component that displays the fetched data.</p><p>Now let’s discuss abstraction. Here, the `App` component remains clean and simple because the data fetching, which was originally handled within the component itself, has now been abstracted into the HOC. By moving this logic to the HOC, we separate concerns, keeping the core component focused on rendering. The HOC becomes even more powerful if we pass the URL as a prop, making it more dynamic and reusable for different data sources. Through this approach, the `App` component stays uncluttered and ready to accommodate additional logic or features as needed, without sacrificing readability or maintainability.</p><p><strong>Method 2: Container-Component pattern</strong></p><p>The Container Component pattern allows us to pass one component as a child to another, creating a reusable structure. Let’s explore a practical use case: in modern SaaS applications, we often want to highlight the hover state of elements like buttons, icons, or other components with custom styling. While we could write separate hover logic for each component, there’s a more efficient way. Instead of duplicating code, we can create a single parent component that handles the hover logic and passes necessary props to its children to reflect the changes. This not only simplifies our code but makes it more maintainable and scalable!</p><pre>import { useDisclosure, UseDisclosureProps } from &quot;@chakra-ui/react&quot;;<br>import React from &quot;react&quot;;<br><br>type AppHoverType = {<br>    children:(props: UseDisclosureProps) =&gt; React.ReactElement;<br>}<br><br>const AppHover: React.FC&lt;AppHoverType&gt; = ({<br>    children<br>}) =&gt; {<br>    const disclosureProps = useDisclosure()<br>    return &lt;&gt;<br>        {children(disclosureProps)}<br>    &lt;/&gt;<br>}<br><br>export default AppHover;</pre><pre>import React from &#39;react&#39;<br><br>const HoverEntity: React.FC = () =&gt; {<br>    return &lt;AppHover&gt;<br>    {({ isOpen: hover, onClose, onOpen }) =&gt; &lt;Box <br>            border={hover ? &quot;1px solid rgb(235, 235, 235)&quot; : undefined} <br>            borderRadius=&quot;2px&quot;<br>            cursor=&quot;pointer&quot;<br>            onMouseEnter={onOpen}<br>            onMouseLeave={onClose}<br>            fontSize={hover ? &quot;20px&quot; : &quot;16px&quot;}<br>        &gt;<br>            Hover Effect!<br>        &lt;/Box&gt;}<br>&lt;/AppHover&gt;<br>}<br><br>export default HoverEntity; </pre><p>In this context, abstraction is demonstrated through the `AppHover` component, which accepts a functional component as a prop. When rendered, `AppHover` passes `DisclosureProps` to this child component. The child could be a button, an icon, or any other element. By receiving these hover-related props, the child component can access and respond to hover states as needed, ensuring that it behaves according to the specified hover requirements. This approach encapsulates the hover logic within `AppHover`, allowing the child components to remain focused on their core functionality while seamlessly integrating with the hover behavior.</p><p><em>Also please note, useDisclosure is not Chakra specific :)</em></p><p><strong>Mothod 3: React.cloneElement</strong> **</p><p>This is the hidden charm of React: the ability to dynamically pass props to a component even if they weren’t included initially. This approach offers tremendous benefits, particularly when it comes to encapsulating logic within the view layer. It’s a powerful technique that can significantly streamline and enhance the flexibility of your components.</p><p>So the usecase we are developing is a ThemeProvider utils class that can pass light or dark theme to underlying components. View the code first.</p><pre>import React from &#39;react&#39;;<br><br>const themes = {<br>  dark: { color: &#39;white&#39;, backgroundColor: &#39;black&#39; },<br>  light: { color: &#39;black&#39;, backgroundColor: &#39;white&#39; },<br>};<br><br>const ThemeProvider = ({ children, theme }) =&gt; {<br>  const themeStyles = themes[theme] || themes.light;<br><br>  return React.Children.map(children, child =&gt;<br>    React.cloneElement(child, { style: { ...child.props.style, ...themeStyles } })<br>  );<br>};<br><br>export default ThemeProvider;</pre><pre>import React from &#39;react&#39;;<br><br>const ThemedComponent = ({ style, children }) =&gt; (<br>  &lt;div style={style}&gt;<br>    {children}<br>  &lt;/div&gt;<br>);<br><br>export default ThemedComponent;</pre><pre>import React from &#39;react&#39;;<br>import ThemeProvider from &#39;./ThemeProvider&#39;;<br>import ThemedComponent from &#39;./ThemedComponent&#39;;<br><br>const App = () =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;Themed Components&lt;/h1&gt;<br>    &lt;ThemeProvider theme=&quot;dark&quot;&gt;<br>      &lt;ThemedComponent&gt;Dark Theme Content&lt;/ThemedComponent&gt;<br>    &lt;/ThemeProvider&gt;<br>    &lt;ThemeProvider theme=&quot;light&quot;&gt;<br>      &lt;ThemedComponent&gt;Light Theme Content&lt;/ThemedComponent&gt;<br>    &lt;/ThemeProvider&gt;<br>  &lt;/div&gt;<br>);<br><br>export default App;</pre><p>Explaination:</p><ol><li><strong>ThemeProvider Component:</strong> Uses React.cloneElement to apply a theme (defined in themes) to each child component. The theme styles are dynamically merged with any existing styles on the child components.</li><li><strong>ThemedComponent Component:</strong> A simple component that displays content with applied styles.</li><li><strong>App Component:</strong> Demonstrates how to apply different themes to ThemedComponent instances using ThemeProvider.</li></ol><p>Implementing this in a real-world codebase would require additional effort, but the core idea is clear. The key abstraction here is that the components within the `App` have no knowledge of the specific details of the dark or light themes. Instead, the themes are seamlessly injected into the underlying components, allowing them to adapt and reflect the appropriate styles without any direct awareness of the theme logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*9rkrM9_lVGXRmgdPCijNZw.png" /><figcaption>Output of Method 3 code example</figcaption></figure><p>Conclustion:</p><p>Here are my top three strategies for achieving abstraction in React. Embracing code abstraction is highly beneficial, and I encourage incorporating these patterns throughout your codebase wherever possible. To deepen your understanding of implementation abstraction, I highly recommend recreating libraries like Formik or React-forms. This exercise will provide valuable insights and enhance your grasp of abstraction concepts. I’d love to hear your thoughts on the blog — feel free to share your feedback!</p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b00b2ab8542" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Middleware Testing in Express with Jest : A Comprehensive Guide]]></title>
            <link>https://medium.com/@eklavya_/effortless-middleware-testing-in-express-with-jest-a-comprehensive-guide-ce9b103571b4?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9b103571b4</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 18:50:40 GMT</pubDate>
            <atom:updated>2024-01-17T18:50:40.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Effortless Middleware Testing in Express with Jest : A Comprehensive Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXCEe1v9f3eDG2Fm6U5wig.jpeg" /><figcaption>by <strong>Negative Space </strong>on Pexels.com</figcaption></figure><p>Navigating the intricacies of Express middleware testing is a crucial skill for any Node.js developer, and Jest stands out as a powerful testing framework to streamline this process. In this blog, we embark on a journey to unravel the mysteries of testing middlewares in Express using Jest. From setting up a robust testing environment to crafting effective test cases, we will explore the techniques and best practices that empower developers to ensure the reliability and efficiency of their Express applications. Let’s dive into the world of middleware testing with Jest, demystifying the process and enhancing our ability to deliver robust and resilient code in a step by step manner.</p><p>Step 1 — Know the requirements</p><p>Below is a typical authentication middleware for express servers with jwt.</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br>const { secretKey } = require(&#39;./config&#39;); // Replace with your own secret key<br><br>const authenticateMiddleware = (req, res, next) =&gt; {<br>  const token = req.header(&#39;Authorization&#39;);<br><br>  if (!token) {<br>    return res.status(401).json({ message: &#39;Unauthorized: No token provided&#39; });<br>  }<br><br>  jwt.verify(token, secretKey, (err, decoded) =&gt; {<br>    if (err) {<br>      return res.status(401).json({ message: &#39;Unauthorized: Invalid token&#39; });<br>    }<br><br>    // Attach the decoded user information to the request object for further use<br>    req.user = decoded;<br>    next();<br>  });<br>};<br><br>module.exports = authenticateMiddleware;</pre><p>To effectively test this function, three arguments must be supplied. When inspecting the first two arguments, it becomes evident that they are substantial objects. Manually replicating these objects is a daunting task, considering their size. Additionally, exporting these objects in an Express-friendly manner is restricted. To streamline the testing process and overcome these challenges, consider employing specialized tools or techniques that facilitate the creation and manipulation of these complex objects, ensuring a more efficient and maintainable testing workflow. The one I use regularly is <a href="https://www.npmjs.com/package/node-mocks-http">node-mocks-http</a>. This friendly and powerful tool helps you create custom express request and response objects that makes our life much easier when testing middlewares in express.</p><p>To create a request object with desired params, body and query parameters, we can use this</p><pre>const request = httpMocks.createRequest({<br>        method: &#39;GET&#39;,<br>        url: &#39;/user/42&#39;,<br>        params: {<br>            id: 42<br>        }<br>    });</pre><p>Also, if you want to add a header with a token and other informations, here you go</p><pre>const request = httpMocks.createRequest({<br>        method: &#39;GET&#39;,<br>        url: &#39;/user/42&#39;,<br>        params: {<br>            id: 42<br>        },<br>        headers: { Authorization: `Bearer ${res.body.tokens.access.token}` },<br>    });</pre><p>And to create a response object, just use the createResponse method provided by the library itself. This can be as simple as</p><pre> const resp = httpMocks.createResponse()</pre><p><strong>Question: How to create the next function ?</strong></p><p>There is a fundamental practice in software testing which says</p><blockquote>Any function borrowed by a function should be mocked during testing.</blockquote><p>Essentially, when a function relies on the code of another function by invoking it with the necessary arguments, it becomes imperative to mock out these dependent functions during testing. Jest provides a powerful mocking feature, allowing the creation of specialized functions through the jest.fn() method. Mocking enables the substitution of the actual function with a custom one that returns specific values, thereby isolating the test scope to the inherent logic of the function under examination. This not only enhances test control but also ensures that the evaluation focuses solely on the function&#39;s internal code, promoting a more targeted and effective testing environment.</p><p>If you want to know more about mocking please refer to this blog.</p><p><a href="https://medium.com/@eklavya_/jest-spy-vs-mock-when-to-use-what-60b8720f3ed0">Jest Spy vs Mock — when to use what!</a></p><p>Having addressed the intricacies of the problem, we can now seamlessly proceed to the testing phase. We are equipped to invoke the middleware efficiently and assess its functionalities. Below, you’ll find an illustrative example of a standard test case designed to evaluate the authentication middleware.</p><pre>test(&quot;returned token is valid for user&quot;, async () =&gt; {<br>      // get a real response from the register api with token<br>      const res = await request(app).post(&quot;/v1/auth/register&quot;).send(newUser);<br>      <br>      const req = httpMocks.createRequest({<br>        headers: { Authorization: `Bearer ${res.body.tokens.access.token}` },<br>      });<br>      const resp = httpMocks.createResponse()<br>      const next = jest.fn(); // mocked the next function<br>      <br>      <br>      await auth(req, resp, next);<br>      <br>      expect(next).toHaveBeenCalledWith(); <br>      expect(req.user.email).toEqual(newUser.email);<br>    });</pre><p>Directing your focus to the concluding assertions in the test, the initial statement employs a specialized Jest matcher called toHaveBeenCalledWith. This assertion verifies whether the subsequent function has been invoked. The successful execution of the middleware implies a seamless transition to the next function. Conversely, a failure indicates a flaw in the process.</p><p>The subsequent assertion scrutinizes the request object for the presence of a property named ‘user.’ In our authentication middleware, we augment the request object with the user information under favorable conditions. Confirming the existence of the user object within the request object serves as a secondary validation, reiterating the successful execution of our middleware. These dual assertions collectively fortify the robustness of our test suite.</p><p>Thank you for your time :)</p><p>If you found value in my blogs, kindly consider supporting me with a virtual coffee. Your encouragement goes a long way and is greatly appreciated.</p><figure><a href="https://www.buymeacoffee.com/eklavya01"><img alt="" src="https://cdn-images-1.medium.com/max/262/1*wdz1SLncRsx72-zrxVao5g.png" /></a></figure><p>Feel free to share any questions or uncertainties you may have. I’m here to assist and provide clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9b103571b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 Questions that can give you a hard time in a React Interview.]]></title>
            <link>https://medium.com/@eklavya_/top-5-questions-that-can-give-you-hard-a-time-in-a-react-interview-2d82bf655ccd?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d82bf655ccd</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Tue, 02 May 2023 09:20:01 GMT</pubDate>
            <atom:updated>2023-05-02T09:22:57.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-MTGBvzTY-2FBJWc0kocA.jpeg" /></figure><p>React is becoming very popular amongst frontend developers day by day and more and more companies adopting the tools and best practices around React for their frontend needs. This is why you would see a surge in openings around React in various companies. With all these developments, it is seen that the expectation from the candidate is also skyrocketing and questions asked are targeting the candidate’s core understanding around React and its best practices. In this blog, I am adding some questions that I faced in my days and those I think can be the next questions you might face.</p><ol><li><strong>What will be printed on the screen when the button is clicked for the first time?</strong></li></ol><pre>import React, { useState } from &quot;react&quot;;<br><br>const App: React.FC = () =&gt; {<br>  const [ count, setCount ] = useState&lt;number&gt;(0)<br><br>  const increaseCount = () =&gt; {<br>    setCount(count + 1)<br>    setCount(count + 1)<br>  }<br><br>  return &lt;div&gt;<br>    &lt;div&gt;Count is {count}&lt;/div&gt;<br>    &lt;button onClick={increaseCount}&gt;+&lt;/button&gt;<br>  &lt;/div&gt;<br>}</pre><p><strong>Answer:</strong></p><p>This is a trick question. Most of us might think it will increase count by 2. But actually, it will end up increasing the count by 1. This is because setCount is an asynchronous function and count increase does not happen in the main thread.</p><p>2. <strong>What will be the output of this code ?</strong></p><pre>import React from &#39;react&#39;;<br><br>class App extends React.Component {<br><br>  state = {<br>    count: 0<br>  }<br><br>  constructor(props: any) {<br>    super(props)<br>    <br>  }<br><br>  handleClick () {<br>    this.setState({<br>      count: this.state.count + 1<br>    })<br>  }<br><br>  render() {<br>    return &lt;div&gt;<br>      &lt;div&gt;Count is {this.state.count}&lt;/div&gt;<br>      &lt;button onClick={this.handleClick}&gt;+&lt;/button&gt;<br>    &lt;/div&gt;<br>  }<br><br>}<br><br>export default App;</pre><p><strong>Answer</strong>:</p><p>This code will lead to error if using TypeScript or else, the count will not increase on button click. In the first case, it will complain that this.setState is not available and throw an error. If you are using JavaScript, the count will not increase because of the nature of context in a regular function. In a regular function ( means created not using arrow syntax ), the context depends on the call site. Here, handleClick does not have access to the component state directly and hence cannot call setState and increment count.</p><p>This have two solutions</p><p>First, bind the component context to the function. Here is the code. Inside the constructor, please find the setup.</p><pre>import React from &#39;react&#39;;<br><br>class App extends React.Component {<br><br>  state = {<br>    count: 0<br>  }<br><br>  constructor(props: any) {<br>    super(props)<br>    this.handleClick = this.handleClick.bind(this)<br>  }<br><br>  handleClick () {<br>    this.setState({<br>      count: this.state.count + 1<br>    })<br>  }<br><br>  render() {<br>    return &lt;div&gt;<br>      &lt;div&gt;Count is {this.state.count}&lt;/div&gt;<br>      &lt;button onClick={this.handleClick}&gt;+&lt;/button&gt;<br>    &lt;/div&gt;<br>  }<br><br>}<br><br>export default App;</pre><p>Apart from this, you can add arrow functions. Arrow functions are known to fetch context from its lexical outer environment. That’s how it will pick the right context from the component.</p><pre>import React from &#39;react&#39;;<br><br>class App extends React.Component {<br><br>  state = {<br>    count: 0<br>  }<br><br>  constructor(props: any) {<br>    super(props)<br>  }<br><br>  handleClickArrow = () =&gt; {<br>    this.setState({<br>      count: this.state.count + 1<br>    })<br>  }<br><br>  render() {<br>    return &lt;div&gt;<br>      &lt;div&gt;Count is {this.state.count}&lt;/div&gt;<br>      &lt;button onClick={this.handleClickArrow}&gt;+&lt;/button&gt;<br>    &lt;/div&gt;<br>  }<br><br>}<br><br>export default App;</pre><p>3. <strong>What will be logged when handleClick below is called</strong> ?</p><pre>// inside a React Component <br><br>state = {<br>   count: 0<br>}<br><br>handleClick = () =&gt; {<br>  this.setState({<br>    count: this.state.count + 1<br>  }, () =&gt; {<br>    console.log(&quot;A &quot;, this.state.count);<br>  })<br>  console.log(&quot;B &quot;, this.state.count);<br>}</pre><blockquote><strong>Answer</strong>: The output here will be <br>B 0 <br>A 1</blockquote><p>This is because setState is an asynchronous method and hence the second log will print first. SetState has the feature of providing a callback function as a second argument that will be triggered after the variable updates. hence, from the first log updated value of count will be printed.</p><p>4. <strong>What will be the displayed inside div with id target below ?</strong></p><pre>import React from &#39;react&#39;;<br><br>const Wrap = (props) =&gt; {<br>  return React.cloneElement(props.children, {<br>    value: &quot;this is a target&quot;<br>  })<br>}<br><br>const App = () =&gt; {<br>  return &lt;Wrap&gt;<br>    &lt;Child /&gt;<br>  &lt;/Wrap&gt;<br>}<br><br>const Child = (props) =&gt; {<br>  return &lt;div id=&quot;target&quot;&gt;{props.value}&lt;/div&gt;<br>}<br><br>export default App;</pre><p><strong>Answer</strong>:</p><p>The div with id <strong>target</strong> will show the content as <em>this is a target</em>. <br>This is actually a question that tests multiple React concepts at the same time. Firstly, the children’s property. React components can take in other components in its opening and closing tags and access that component in children property in its props. On top of it we are calling React.cloneElement which can clone components and provide any other prop we want to pass apart from those it already has. That’s why Child receives the value prop from Wrap even though it is not directly provided from the App component.</p><p>5. <strong>What will happen when button in App component is clicked </strong>?</p><pre>import React from &#39;react&#39;;<br><br>const FancyButton = React.forwardRef((props, ref) =&gt; (<br><br>  const [ count, setCount ] = useState(0) <br><br>  const handleClick = () =&gt; {<br>    setCount(count + 1)<br>  }<br><br>  return &lt;button ref={ref} onclick={handleClick}&gt;<br>    {count} times clicked!<br>  &lt;/button&gt;<br>));<br><br>const App = () =&gt; {<br>  const ref = React.createRef();<br><br>  const handleClick = () =&gt; {<br>    if(!ref.current) return<br>    ref.current?.click()<br>  }<br><br>  return &lt;&gt;<br>    &lt;FancyButton ref={ref} /&gt;<br>    &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;<br>  &lt;/&gt;;<br>  <br>}</pre><p><strong>Answer</strong>:</p><p>It will increment the state in FencyButton component. This is happening due to Forward Referencing React components. Here a ref is passed from parent to child and then parent get to command certain things in the child. In this case, we are adding the ref to child component’s button element. Hence, we can click it from the the parent component itself by using the ref. This is the only way to pass a ref between components in React.</p><p>These are some of the questions in my mind that can be tricky to solve in an interview. Let me know your thoughts about them. Also, below are a few other posts that will assist you in your preparation. Thanks and hit that clap button :)</p><p><a href="https://medium.com/@eklavya_/lets-create-our-very-own-promise-all-84a4e724b030">Lets create our very own Promise.all!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d82bf655ccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lets create our very own Promise.all!]]></title>
            <link>https://medium.com/@eklavya_/lets-create-our-very-own-promise-all-84a4e724b030?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a4e724b030</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 17:03:59 GMT</pubDate>
            <atom:updated>2023-02-24T17:03:59.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMavrdrNhbBxr-Ku6Is5Sw.jpeg" /></figure><p>Let me start with this,</p><p><strong>Creating your own Promise.all is what some smart JavaScript minds might ask you during an interview</strong>. Lets attempt to be ready for it with this blog.</p><p><strong>Understanding the question</strong>:</p><p>Create your own Promise.all polyfill. In other words, please create your own Promise.all implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMavrdrNhbBxr-Ku6Is5Sw.jpeg" /></figure><p>Let’s first understand what Promise.All does. This is a function that takes an array of promises and returns a new promise that resolves with an array of all the results from the individual promises. Lets see an example.</p><pre>// 3 promises <br>const p1 = new Promise((resolve, reject) =&gt; {<br>  resolve(&#39;P1&#39;)<br>})<br><br>const p2 = new Promise((resolve, reject) =&gt; {<br>   setTimeout(() =&gt; {<br>    resolve(&#39;P2&#39;)<br>   }, 1000);<br>})<br><br>const p3 = new Promise((resolve, reject) =&gt; {<br>   setTimeout(() =&gt; {<br>    resolve(&#39;P3&#39;)<br>   }, 0);<br>})<br><br>const p4 = &#39;some rendom string&#39;<br><br>Promise.all([p1, p2, p3, p4]).then(data =&gt; {<br>  // TODO: data<br>console.log(data)<br>}).catch(e =&gt; {<br>  // Error triggered if any of these promises fails. <br>})<br><br>// Output: [ &#39;P1&#39;, &#39;P2&#39;, &#39;P3&#39; ] &lt;= returned from then block</pre><p>We will go step by step.</p><p><strong>Step 1: Create a function that takes an array of promises and returns a promise.</strong></p><p>This is very simple.</p><pre>// Custom Promise.All <br><br>const allX = (promiseArr) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    // TODO: core implementation. <br>  });<br>}</pre><p><strong>Step 2: Run All the promises in the array. Reject the promise if any one fails.</strong></p><pre>// Custom Promise.All <br><br>const allX = (promiseArr) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>     promiseArr.forEach((promise, index) =&gt; {<br>        promise.then((data) =&gt; {<br>          <br>        }).catch(e =&gt; {<br>          // reject when any of the promises fails. <br>           reject(e)<br>        })<br>     })<br>  });<br>}</pre><p><strong>Step 3: Resolve with an array of responses after all promises are resolved</strong>.</p><p>This involves two steps.<br>- create an array and store the responses coming from the promises.<br><strong>-</strong> Call resolve after all promises are done. For that we will keep a count.</p><pre>// Custom Promise.All <br><br>const allX = (promiseArr) =&gt; {<br>  const responses = []<br>  let count = 0; <br>  return new Promise((resolve, reject) =&gt; {<br>     promiseArr.forEach((promise, index) =&gt; {<br>        promise.then((data) =&gt; {<br>          responses[index] = data; <br>          count ++<br>          <br>          // check to resolve. <br>          if (promiseArr.length === count) {<br>            resolve(responses)<br>          }<br>        }).catch(e =&gt; {<br>          // reject when any of the promises fails. <br>           reject(e)<br>        })<br>     })<br>  });<br>}</pre><p><strong>Step 4: Make it available at Promise object</strong></p><p>Finally, make it available at the promise object itself.</p><pre>Promise.allX = allX</pre><p><strong>Step 5: Handle edge case</strong></p><p>Till now we are in great shape with our own Promise.all. But, we need to handle some edge cases here. Promise.all works very well even with items being not a promise (like p4 ). We need to handle the scenario in our code so that non promise expressions in the array are also handled nicely. For that we will use the Promise.resolve function to convert these values to a always resolving promise..</p><pre>const allX = (promiseArr) =&gt; {<br>  const responses = []<br>  letcount = 0; <br>  return new Promise((resolve, reject) =&gt; {<br>     promiseArr.forEach((value, index) =&gt; {<br>         let promise = value;<br>        // check if valid promise <br>        if(!(value instanceof Promise)) {<br>            promise = Promise.resolve(value)<br>        }<br>        promise.then((data) =&gt; {<br>          responses[index] = data; <br>          count ++<br>          <br>          // check to resolve. <br>          if (promiseArr.length === count) {<br>            resolve(responses)<br>          }<br>        }).catch(e =&gt; {<br>          // reject when any of the promises fails. <br>           reject(e)<br>        })<br>     })<br>  });<br>}</pre><p>This will be enough for keep things going. Questions ?? Feel free to ask.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a4e724b030" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest Spy vs Mock — when to use what!]]></title>
            <link>https://medium.com/@eklavya_/jest-spy-vs-mock-when-to-use-what-60b8720f3ed0?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b8720f3ed0</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[spy]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 02:07:04 GMT</pubDate>
            <atom:updated>2025-04-25T08:39:53.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jest Spy vs Mock — when to use what!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5AZSs0DjG8aGnHyE5ecqw.jpeg" /><figcaption>By Kevin Ku on pexels.com</figcaption></figure><p>If you are stuck with Jest Spying and mocking and not sure of when to use which one of these, this is your blog!</p><p>Let’s understand this step by step; with some associated concepts and code examples.</p><p><strong>What is testable code!</strong></p><p>Your code is testable if it returns the same output for a given set of inputs, regardless of environments. An environment can be</p><p>1. Database<br>2. Time of day<br>3. System delays<br>4. Network delays<br>5. OS/ System configuration</p><p>Let’s understand it with an example.</p><pre>/**<br>* Function returns morning, afternoon or evening <br>* depending on when it is called<br>*/<br>const whatTimeItIs = () =&gt; {<br>  const date = new Date()<br>  const hour = date.getHours()<br>  if (hour &lt; 12) return &quot;morning&quot;<br>  if (hour &lt; 16) return &quot;afternoon&quot;<br>  return &quot;evening&quot;<br>}</pre><p>Above is an untestable code. Simply because it will give you different output depending on when you call the function, failing all your assertions.</p><p><strong>How to test untestable code !</strong></p><p>Simple answer to this is spying. Spying is the process of looking for a specific function and returning <strong>a different value when it is called </strong>(like a trap).In our function above, the only reason it is untestable, because the Date function returns a different timestamp every time it is called. We proxy this and return a unique value every time you end up writing stable test cases.</p><p>Jest Spying is done via a function called <strong>spyOn</strong>. Below is an example of how to do it.</p><pre>describe(&#39;What time is it:&#39;, () =&gt; {<br><br>    it(&#39;Verify that 15 returns afternoon&#39;, () =&gt; {<br>        const mockDate = new Date(2021, 3, 24, 15, 0, 30, 0)<br><br>        // Create a system spy.<br>        const spy = jest.spyOn(global, &#39;Date&#39;);<br>        spy.mockImplementationOnce(() =&gt; mockDate);<br>        <br>        let output = functions.whatTimeIsIt();<br><br>        expect(output).toEqual(&#39;afternoon&#39;);<br>        // Check if the spy was called<br>        expect(spy).toHaveBeenCalledTimes(1);<br>    });<br>})</pre><p>What’s happening above ?</p><p>1. A date object is created that points to a specific time. (mockDate)<br>2. jest.SpyOn set to look for Date function call which belongs to the global object. This is the trap we set.<br>3. Next line simply says what value to return when the Date function is triggered. This value will be returned only once. Subsequent calls to Date will not be affected.<br>4. You are all set to test the function.</p><p><strong>So, whenever you face code which is untestable, please use jest spying to deal with it. </strong>And<strong> </strong>please do not forget to remove the traps after each test you write. This is how it is done</p><pre>describe(&#39;What time is it:&#39;, () =&gt; {<br>    afterEach(() =&gt; {<br>        // Restore original implementation<br>        global.Date.mockRestore();<br>    })<br>//... rest of the code </pre><blockquote>Note: You can also make it testable by making date an argument to the function. This is smart, but will it always help !!</blockquote><p>Mocking is an equally important concept in testing which you might end up using more frequently. When you write code for production, frequently you will find that some function is internally calling some other functions to do their job. When we are testing our code ( specifically unit testing), we want to be as much specific and want to test the function and not on something it depends on. Also, any bug on these dependent functions might cause our tests to fail. This is where we use mocking. This is done by <strong>jest.fn </strong>function.</p><p>Let’s understand the code below. We have two files, utils.js and support.js. Utils exports a function which depends on some functions provided by support.</p><pre>// utils.js <br>const { support } = require(&quot;./support&quot;)<br><br>/** a function to perform some calculation */<br><br>const performSomeCalculation = (a: number, b:number) =&gt; {<br>  const value = support(a, b);<br>  return value * b;<br>}</pre><pre>// support.js <br>const support = (a: number, b: number) =&gt; {<br>  // does something fragile. <br>  return a ** b;<br>}<br>module.exports = { support }</pre><p>Now let’s try to test the utils function with some mocks in place. Below is a code sample.</p><pre>const deps = require(&quot;./support&quot;)<br>const performSomeCalculation = require(&quot;./utils&quot;)<br><br>describe(&#39;PerformSomeCalculation&#39;, () =&gt; {<br>    it(&quot;should return x for y, z&quot;, () =&gt; {<br>        const mockSupport = jest.fn();<br>        deps.support = mockSupport.mockReturnValue(5) // let&#39;s say<br>        const value = performSomeCalculation(5, 7);<br>        expect(value).toEqual(35)<br>        // it passes <br>    })<br>})</pre><p>Let’s understand what’s going on<br>1. create a mockSupport function with jest.fn. This is our mock. <br>2. add a return value of 5. <br>3. call the function <br>4. Assert with a value which is nowhere near the correct value. (please donot confuse here )</p><p>This is mocking.</p><p><em>What the …. !</em></p><p>Yes, knowing every time about them makes you more confused. Let me point out what you are missing here.</p><blockquote>The main difference in spying and mocking is, when you are spying you are not undermining the entire function implementation, rather you are just targeting a few lines of code which is making it untestable. But in mocking, you are undermining the entire function implementation and you are just returning the value.</blockquote><p><strong>When to use what</strong></p><p>As a rule of thumb, always use spy when you face an untestable code.</p><p>Use mock when you see your function being critically dependent on other functions. You must mock those functions in such cases.</p><p>Below diagram will help keep things together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7SE_XFFU9D3yOzCWY4Vkg.png" /><figcaption>spy vs mock ( jest)</figcaption></figure><p>Let me know your doubts :)</p><p>Also, if you are liking the content I am producing, then do buy me a coffee :)</p><figure><a href="https://www.buymeacoffee.com/eklavya01"><img alt="" src="https://cdn-images-1.medium.com/max/262/1*wdz1SLncRsx72-zrxVao5g.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b8720f3ed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compound component pattern — A way of developing React apps differently.]]></title>
            <link>https://levelup.gitconnected.com/compound-component-pattern-a-way-of-developing-react-apps-differently-8efdd3ce4a8a?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8efdd3ce4a8a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 13:49:26 GMT</pubDate>
            <atom:updated>2020-11-02T04:19:43.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNl_EtkUnd6Qm9WNOWC_gg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@kaboompics?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Kaboompics .com</strong></a> from <a href="https://www.pexels.com/photo/geometric-decoration-5836/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a></figcaption></figure><p>Recently I have developed and published my very first npm package by the name react-capsules. This is a piece of code that can be used in any react app and create a UI component as in the image below. Just fire npm i react-capsules and find it at your service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*LllMwpsbaZJubzEhe0eeuw.gif" /><figcaption>Reusable UI component served by react-capsules.</figcaption></figure><p>Now if you look at its markdown you will find that components are being called using a dot operator. You are not passing many props to a single component and if you are using the package for a while, you will feel better control over the code. The code you developed is not messy and easily understandable and there is no single point of failure while using this library. Similar designs you can find in a very popular react library <a href="https://www.npmjs.com/package/react-bootstrap">react-bootstrap</a>. From above, this design pattern in react is called a compound component pattern. From inside we will find out next.</p><p><strong>What’s the need:</strong></p><p>React has been a great tool from day one it came outside Facebook. But soon developers started to find some limitations in it. One such issue is when passing props deeper from component to component. Issues in a longer prop chain are:</p><ol><li>It is easy to lose track of what’s happening in the code. Making sense of such code is not easy for the first time.</li><li>As react props are unidirectional and immutable, a developer has to maintain a call back chain to change props in the upper nodes of the component tree which can get tedious very easily.</li></ol><p>One can validly argue that we have Redux to take care of such problems where we centralize our store and all manipulate that store. But I argue to look at the problem at hand. Does a UI library like react-capsules need Redux? Is it big enough to be dealt like that? Also, even if we re-engineer the package to use Redux will it give the convenience and control over code like we are having now?</p><p>A good solution to such a problem is not to pass the props but to expose the components to the root. And that’s what compound component pattern (aka CCP) accomplishes. This way you have one state in the app and no props chain. This is the philosophy on which the design pattern is developed on.</p><p><strong>Quick Demo:</strong></p><p>Creating a react app or part of it using CCP is not that difficult. We are just exposing the child components to the root instead of passing off props. To understand better, I will refer to the main project that developed react-capsules.</p><pre>import React from &#39;react&#39;;<br>import Item from &#39;./Item&#39;;<br>import TextInput from &#39;./TextInput&#39;;</pre><pre>const ReactBulletDnd = ({ children, style, data, set }) =&gt; {<br>  return (&lt;div style={{ ...style }}&gt;<br>    &lt;div style={{<br>      display: &#39;flex&#39;,<br>      flexDirection: &#39;row&#39;,<br>      flexWrap: &#39;wrap&#39;<br>    }}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  &lt;/div&gt;)<br>}</pre><pre>ReactBulletDnd.Item = Item;<br>ReactBulletDnd.TextInput = TextInput;</pre><pre>export default ReactBulletDnd;</pre><p>This is the component that is the entry point for the library. In the imports, Item is each of the tabs in the list and TextInput is the input in the bottom section. In the bottom before the exports, you can see how we assign the components just imported to the root component. And we assign all the children to the return function. This is how a typical CCP design is achieved in a react app.</p><p><strong>React.cloneElement</strong></p><p>This is a very handy utility when it comes to implementing CCP. In the context of react-capsules you can see that the drag and drop feature is taken care of by the library. No events are caught or emitted at the call sight or the feature is implemented at a place outside the call sight. This is being done with the help of React.cloneElement. The typical implementation of it is given below.</p><pre>React.Children.map(children, (child) =&gt; {                                   <br>   return React.cloneElement(child, { /*Props here*/ }); <br> }<br>}</pre><p>React.cloneElement helps you pass any prop to a child otherwise passed to it directly. This is a great tool to pass any prop to a component that is needed to achieve a feature but not needed to be seen by the call sight. In our case, events related to drag and drop such as onMouseOver, onMouseEnter etc are passed using this very utility. Please refer to the complete code to have a better idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc091fa43033c0a86ee2b2e68850a94/href">https://medium.com/media/4cc091fa43033c0a86ee2b2e68850a94/href</a></iframe><p>As you can see in the gist, we are passing a few props like onClick, onDragStart, etc in the cloneElement method if the child is not a textInput. You can see it in line number 39 to 46 in the gist. This is how the library masks the drag and drop implementation from the call sight.</p><p><strong>Conclusion:</strong></p><p>By now, the article explains the problem CCP solves and a typical implementation of it. Also, we discussed masking of features using React.cloneElement. Do you think this type of design can replace Redux in your react app? Comment your thoughts. Also, find the code of the library below.</p><p><a href="https://github.com/Gaurav2048/React-Capsules">Gaurav2048/React-Capsules</a></p><p>React-Capsules at npm-js. Help me make it a tool of choice.</p><p><a href="https://www.npmjs.com/package/react-capsules">react-capsules</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8efdd3ce4a8a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/compound-component-pattern-a-way-of-developing-react-apps-differently-8efdd3ce4a8a">Compound component pattern — A way of developing React apps differently.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing React Drag and Drop without any external library.]]></title>
            <link>https://medium.com/@eklavya_/implementing-react-drag-and-drop-without-any-external-library-d7ec00437afb?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ec00437afb</guid>
            <category><![CDATA[dnd]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 20:59:46 GMT</pubDate>
            <atom:updated>2024-01-16T18:53:06.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*bZf7_RLAIwLuGCo3LyEF3A.gif" /><figcaption>React-DnD in use</figcaption></figure><p>This article will explain how to achieve drag and drop feature in React with little effort. Drag and drop is a very widely seen easy to use feature that adds great convenience to your users. But it is always a huge task if implemented using vanilla JavaScript as it will include huge calculations depending on its implementation (such as dropping in a list ). But React comes up very handy in drag and drop (or simply dnd) feature. Here we will see it in action by implementing a simple drag and drop list. The learnings can easily be used to create complex dnd applications such as one in the gif above. If you look closely, you will see a list with 2 levels (blue and black childs) and while each inner child (in black) can be dragged to the other lists, you can also shuffle each child (in blue) in the outer list as well. Find the live implementation and code for the big project below.</p><ul><li><a href="https://5f1c9325bc6a87204a5e0bcc--react-multilevel-dnd.netlify.app/">React App</a></li><li><a href="https://github.com/Gaurav2048/React-DnD-Adv">Gaurav2048/React-DnD-Adv</a></li></ul><p>Now let us how easy it is to implement a dnd feature in React. Let us go step by step.</p><blockquote><em>Want to read this story later? Save it in </em><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=blog&amp;utm_campaign=noteworthy&amp;utm_content=eid7"><em>Journal</em></a><em>.</em></blockquote><p><strong>STEP 1:</strong> <br>Let us create a list first with its children being draggable. This will be a very simple code so will refrain from explaining. Only catch here is the <strong>draggable </strong>prop<strong> </strong>passed to every h1 which is making the children draggable. Hence on drag, you can see a shadow of the child moving around.</p><pre>import React, { useState } from ‘react’;</pre><pre>import ‘./App.css’;</pre><pre><strong>const</strong> App = () <strong>=&gt;</strong> {</pre><pre><strong>const</strong> [list, setList] = useState([<br>‘Chicken Biriyani’,<br>‘Mutton Pulao’,<br>‘Paneer Masala’,<br>‘Tandoori Chicken’,<br>‘Dal Makhana’,<br>‘Malai Kofta’,<br>]);<br>// <em>All dishes above. Indian</em></pre><pre>return (<br>&lt;&gt;<br>{<br> list &amp;&amp;<br>  list.map((item, index) <strong>=&gt;</strong> (<br>     &lt;h1 key={index} draggable&gt;<br>       {item}<br>     &lt;/h1&gt;<br>    ))}<br>   &lt;/&gt;<br>  );<br>};<br>export default App;</pre><p>The css file is given bellow (App.css)</p><pre>* {<br>  box-sizing: border-box;<br>}</pre><pre>html,<br>body,<br>#root {<br>  width: 100%;<br>  height: 100%;<br>  padding-top: 40px;<br>}</pre><pre>h1 {<br>  background-color: white;<br>  color: #222222;<br>  font-size: 16px;<br>  font-weight: 800;<br>  margin-right: 30%;<br>  margin-left: 30%;<br>  padding: 10px;<br>  cursor: move;</pre><pre>}</pre><p>The output on the browser will look similar to the image bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzVX_dKslWQkgP8sLuvLtg.png" /><figcaption>A draggable list.</figcaption></figure><p><strong>STEP 2:</strong> <br>Now that our list is draggable, the next task is to keep track of the item being dragged. At any given time, only one child can be in the drag state. Hence, we will be using a ref to keep track of the child by its position. This will be done in the onDragStart listener attached to every child in the list. Get the code below.</p><pre>import React, { useState, useRef } from &#39;react&#39;;<br>import &#39;./App.css&#39;;</pre><pre><strong>const</strong> App = () <strong>=&gt;</strong> {</pre><pre><strong>const</strong> draggingItem = useRef();</pre><pre><strong>const</strong> [list, setList] = useState([<br> &#39;Chicken Biriyani&#39;,<br> &#39;Mutton Pulao&#39;,<br> &#39;Paneer Masala&#39;,<br> &#39;Tandoori Chicken&#39;,<br> &#39;Dal Makhana&#39;,<br> &#39;Malai Kofta&#39;,<br>]);</pre><pre><strong>const</strong> handleDragStart = (e, position) <strong>=&gt;</strong> {<br>  draggingItem.current = position;<br>  console.log(e.target.innerHTML);<br>};</pre><pre>return (<br>&lt;&gt;<br>{<br>list &amp;&amp;<br> list.map((item, index) <strong>=&gt;</strong> (<br>  &lt;h1 <br>   onDragStart={(e) <strong>=&gt;</strong> handleDragStart(e, index)}<br>   key={index} draggable&gt;<br>     {item}<br>   &lt;/h1&gt;<br>  ))}<br> &lt;/&gt;<br> );<br>};</pre><pre>export default App;</pre><p><strong>STEP 3: </strong><br>Now that we are tracking the child being dragged around, we will try to find over which child it is hovering at any given time. For that we will use one more ref and change it whenever our child hovers on another child. It will be done using the onDragEnter listener. Find the code below.</p><pre>import React, { useState, useRef } from &#39;react&#39;;<br>import &#39;./App.css&#39;;</pre><pre><strong>const</strong> App = () <strong>=&gt;</strong> {</pre><pre><strong>const</strong> draggingItem = useRef();<br><strong>const</strong> dragOverItem = useRef();</pre><pre><strong>const</strong> [list, setList] = useState([<br> &#39;Chicken Biriyani&#39;,<br> &#39;Mutton Pulao&#39;,<br> &#39;Paneer Masala&#39;,<br> &#39;Tandoori Chicken&#39;,<br> &#39;Dal Makhana&#39;,<br> &#39;Malai Kofta&#39;,<br>]);</pre><pre><strong>const</strong> handleDragStart = (e, position) <strong>=&gt;</strong> {<br> draggingItem.current = position;<br> console.log(e.target.innerHTML);<br>};</pre><pre><strong>const</strong> handleDragEnter = (e, position) <strong>=&gt;</strong> {<br> dragOverItem.current = position;<br> console.log(e.target.innerHTML);<br>};</pre><pre>return (<br>&lt;&gt;<br>{<br>list &amp;&amp;<br>list.map((item, index) <strong>=&gt;</strong> (<br>  &lt;h1<br>   onDragStart={(e) <strong>=&gt;</strong> handleDragStart(e, index)}<br>   onDragEnter={(e) <strong>=&gt;</strong> handleDragEnter(e, index)}<br>   key={index}<br>   draggable<br>    &gt;<br>     {item}<br>   &lt;/h1&gt;<br>   ))}<br>  &lt;/&gt;<br>  );<br> };</pre><pre> export default App;</pre><p>Verify your progress by finding the name of the child in the console over which you are dragging the other child.</p><p><strong>STEP 5: <br></strong>Our last step is to reshuffle the list when you finally drop the element over any of the other children. Till now we have the index of the dragged child and the child over which it is being dragged making the reshuffle of our list an easy operation.</p><pre>import React, { useState, useRef } from &#39;react&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre><strong>const</strong> App = () <strong>=&gt;</strong> {</pre><pre><strong>const</strong> draggingItem = useRef();<br><strong>const</strong> dragOverItem = useRef();</pre><pre><strong>const</strong> [list, setList] = useState([<br> &#39;Chicken Biriyani&#39;,<br> &#39;Mutton Pulao&#39;,<br> &#39;Paneer Masala&#39;,<br> &#39;Tandoori Chicken&#39;,<br> &#39;Dal Makhana&#39;,<br> &#39;Malai Kofta&#39;,<br>]);</pre><pre><strong>const</strong> handleDragStart = (e, position) <strong>=&gt;</strong> {<br> draggingItem.current = position;<br> console.log(e.target.innerHTML);<br>};</pre><pre><strong>const</strong> handleDragEnter = (e, position) <strong>=&gt;</strong> {<br> dragOverItem.current = position;<br> console.log(e.target.innerHTML);<br>};</pre><pre><strong>const</strong> handleDragEnd = (e) <strong>=&gt;</strong> {</pre><pre><strong>const</strong> listCopy = [...list];</pre><pre><strong>const</strong> draggingItemContent = listCopy[draggingItem.current];<br>listCopy.splice(draggingItem.current, 1);<br>listCopy.splice(dragOverItem.current, 0, draggingItemContent);<br> <br> draggingItem.current = null;<br> dragOverItem.current = null;<br> setList(listCopy);<br>};</pre><pre>return (<br>&lt;&gt;<br>{<br> list &amp;&amp;<br> list.map((item, index) <strong>=&gt;</strong> (<br>  &lt;h1 <br>   onDragStart={(e) <strong>=&gt;</strong> handleDragStart(e, index)}<br>   onDragEnter={(e) <strong>=&gt;</strong> handleDragEnter(e, index)}<br>   onDragEnd={handleDragEnd}<br>   key={index}<br>   draggable<br>    &gt;<br>      {item}<br>    &lt;/h1&gt;<br>   ))}<br>  &lt;/&gt;<br> );<br>};</pre><pre>export default App;</pre><p>Our drag and drop list in React is ready. But we can do much better on top of our current progress. Specially two things I want to mention now.</p><ol><li><strong>Getting rid of the drop animation:</strong></li></ol><p>While we drop the dragging child, we can see its shadow is trying to go back to its original position. This can leave the user with an impression that the dnd is not happening. This effect can be prevented by adding this line in every child.</p><pre>onDragOver={(e) =&gt; e.preventDefault()}</pre><p>2. <strong>Reshuffle the list on Drag:</strong></p><p>Currently our app reshuffles the list on every drop. But we can make our list reshuffle whenever the dragged child enters another child. This will make the feature more live and appealing. Also, it is just a few lines change above our current work. For that we will merge the two functions <strong>handleDragEnter</strong> and <strong>handleDrop. </strong>Also, we will change the draggingItem ref to the dragOverItem ref after every time a reshuffle happens. By doing this we are making sure that the code we run in onDropEnd runs every time when the dragged child enters a new child. The modified code is given below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5187dd0ab43217369291b7a4e4e0dea1/href">https://medium.com/media/5187dd0ab43217369291b7a4e4e0dea1/href</a></iframe><p>This will add up making our list much more interective with its dnd feature. The gif below will give an account of the dnd operation in the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*aNoT2Qx3i22cp6BUVvJ3Ug.gif" /><figcaption>Final work.</figcaption></figure><p>Feel free to add desired css during the drag state.</p><p>Thanks for checking out!</p><p>Also, if you liked this, do buy me a coffee. Thanks for the support in advance :)</p><figure><a href="https://www.buymeacoffee.com/eklavya01"><img alt="" src="https://cdn-images-1.medium.com/max/262/1*wdz1SLncRsx72-zrxVao5g.png" /></a></figure><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ec00437afb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why React should be your choice for web application development.]]></title>
            <link>https://medium.com/weekly-webtips/why-react-should-be-your-choice-for-web-application-development-2a876aade9ed?source=rss-b9e36b4d676e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a876aade9ed</guid>
            <category><![CDATA[insights]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gunjan Kalita]]></dc:creator>
            <pubDate>Mon, 20 Jul 2020 21:04:36 GMT</pubDate>
            <atom:updated>2020-07-29T09:52:09.498Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why React should be your choice for web application development?</h3><figure><img alt="Why React should be your choice for web application development?" src="https://cdn-images-1.medium.com/max/1024/1*QnydvovqM-KoYL5FbmPGmw.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/@mateusz-dach-99805">Mateusz Dach</a> on <a href="https://www.pexels.com/">pexels.com</a></figcaption></figure><p>This story is created for those developers and managers who are considering to move out from traditional web development and adopt better libraries and framework for their services or products. It discusses about React which a front end library created by Facebook for web UI development and how it provides similar experience to a desktop application.</p><p>Table of content:</p><ol><li>What is React?.</li><li>How React is different from traditional web development.</li><li>What is create-react-app.</li><li>Advantages of using React.</li><li>Disadvantages of using React.</li><li>Work around.</li></ol><p>So, let’s start.</p><h3><strong>What is React:</strong></h3><p>The official documentation of React explains it like this</p><pre>A JavaScript <strong>library</strong> for <strong>building user interfaces. </strong></pre><p>React is a library and it is designed to create user interfaces. Now, most of us might be in an impression of React being a framework. Also, we were cool with creating our user interfaces with HTML and CSS, so why should React be used. Let me explain.</p><ol><li><strong>Difference between a library and a framework: <br></strong>While both of them are designed to make a developer’s life easier and do complicated tasks for them, a library can possibly be a smaller version of a framework which is <strong>specialised in doing one thing</strong>. A framework on the other hand, brings in more of these libraries together and helps us in solving bigger problems and mostly makes a lot of smart design decisions by themselves. Hence, a library may seem to be more flexible in its implementation, whereas a framework stands rigid and can make you bend to its unique way of solving a problem.</li><li><strong>An User interface library : <br></strong>React provides a declarative way of building user interfaces. This is because you instruct React of what you want to be shown in the browser and React creates the UI for you. A valid argument is HTML is also declarative so how React becomes different. I say, HTML can only be used to generate static content while React can generate dynamic content using a declarative programming approach. Also, what it generates is a Single page application.</li></ol><h3><strong>How React is different from traditional web development:</strong></h3><p>To understand how React is different in its approach, let us create an application to see React and traditional web development workings side by side. It will contain two files, one is an HTML file and a JavaScript file. Code is given below. I highly encourage you to see the code in action by yourself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d94caa23ecd35847554e11f727829524/href">https://medium.com/media/d94caa23ecd35847554e11f727829524/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a85b853a132c98c2d34211a32291c888/href">https://medium.com/media/a85b853a132c98c2d34211a32291c888/href</a></iframe><p>A short explanation of the code…</p><p>We have an HTML file that contains two div , one is manipulated by vanilla javascript and another by the React libraries that are brought from the React CDN. The <strong>script.js </strong>file has a setInterval call that updates both the div in one second interval. Both divs are similar in terms of what it contains; an input, a paragraph element with the current timestamp, and some text.</p><p>Below is an account of what is happening behind the scene when we run the code in a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vhAcTsZirwW0kirMwMz2Og.gif" /><figcaption>View from the inspector window</figcaption></figure><p>If you look at the render cycle in both the divs during update, the fundamental difference of its working will be clear. While our old method is completely rendering the div, the React library is just rendering the HTML element in the DOM that needs update and leaving the rest intact. This strategy comes in with huge performance improvements in large web applications and creates a foundation for providing desktop app-like experience while inside a browser. I am covering this in the section of <strong>Advantages of using React </strong>in more detail<strong>.</strong></p><h3><strong>What is create-react-app:</strong></h3><p>It is a set of libraries combined together using NPM to create a pleasant development experience with React. This includes <br> 1. React Library that helps manipulating DOM elements as shown in the example above and provides a lot of helper utility to optimise your React app for performance and testability. <br> 2. React DOM library to help write to the browser DOM. React cannot write to the DOM on its own. <br> 3. WebPack to provide developer comfort. It brings features like local server, hot reload, project build etc. <br> 4. <a href="https://babeljs.io/">Babel</a> <br> 5. NPM or Node package manager. With the help of NPM, developers get to add work from other developers hosted in the NPM servers as libraries and improve their productivity. Also, it makes managing those libraries and updating them a breeze. <br>I believe create-react-app qualifies to be called a framework as it stands rigid in certain approaches. For example, when you type npm start, it fires up the WebPack server and shows up your app in the browser. It provides some cool features like the hot reload but this is not the only (or necessary) way to start a react app. We can work without them.</p><h3><strong>Advantages of using React:</strong></h3><ol><li><strong>Speed:<br></strong>The example above shows how React is very specific while updating DOM elements. This happens through a data structure that React calls virtual DOM. The React library maintains an equivalent object of the DOM tree in memory which it compares while update with the current DOM. After this diffing process, those elements are found which needs update and instructions are issued to update them. The process of creating virtual DOM from real HTML elements is called <strong>Rendering </strong>in React. The one which writes the real DOM after the diffing process is called <strong>Reconciliation. </strong>For<strong> </strong>large codebase where virtual DOM is huge, React employs heuristic based algorithms to bring performance in the app out of the box. Hence, in the majority of the cases in React, your app will be super performant with no additional cost to bear.</li><li><strong>Rich User experience: <br></strong>To understand this point better, I encourage you to move back to the example I provided and try to type in the input in both the divs. I am sure you will be overwhelmed to see that hardly anything can be typed in the first input as the text goes away and the focus is lost etc. But the one maintained by React just works fine. This again shows virtual DOM in action. The entire DOM tree is never updated which is retaining the earlier instance of the input and hence the text never goes away. Now this is a feature that could earlier provided by native applications only, using a thread or so. But while dealing with the single threaded JavaScript, React brings in similar features to your website. This where React bridges the gap between a native desktop app and a web application.</li><li><strong>Reactive Programming: <br></strong>While reactive programming is comparatively new in native app developments , React adopted a reactive style of implementation right from its inception and hence got the name React. This reactive feature has all to do with the virtual DOM. The <strong>setState</strong> function is there to trigger the Rendering and Diffing process. The process of Reconciliation is so well implemented that the final output gives a near instant update. All these without even a single listener binded or any difficult concept of implementation associated with it. This adds greatly to the developer’s satisfaction.</li><li><strong>Component : <br></strong>A React app is all built with components. They have cool properties like lifecycle methods, props and states that help making the application code base highly modular and reusable. Also, tools like Redux are a great friend when it comes to promote decoupling in the components and single state of information inside the application that makes a huge codebase easier to understand. Also, design patterns like Compound Component patterns (CCP) can improve the overall quality of a React codebase.</li><li><strong>Cross browser Support: </strong><br>React handles a lot of hectic task for you in order to make your app support in multiple browser. One example of this is <strong>Synthetic events </strong>in React. These are cross browser support around brower’s native events. React’s click event <strong><em>onClick, </em></strong>focus event <strong><em>onFocus </em></strong>etc are all examples of synthetic events provided by the library.</li><li><strong>How you benefit as a owner:<br></strong>React is a UI library and applications created with React uses Ajax calls to fetch data from Server. Hence, you create one single API for all of your client applications like your mobile or desktop apps and your web apps. User experience you get is just fabulous. Also, if you are a startup and thinking of having a mobile app that runs both in android and iOS devices, you do not need a native mobile development expert any more. Your React developer very easily can give you mobile apps using the same skill sets using another technology called React-native. Studies show that companies are saving almost 30% in their development cost when they opt for developers comfortable with frameworks like React-native or <a href="https://flutter.dev/">flutter</a>. This approach though has some drawbacks which is a huge discussion in itself. Comment and let me know if you want some insight on this.</li></ol><h3><strong>Disadvantages of using React:</strong></h3><p>Disadvantages of React are very few. But, they are enough to hit your business like a hammer and you should know about this before you make any decision. <strong>React based SPA sucks when it comes to SEO. </strong>High chance is there that web crawlers may never get to index your website. This is due to the declarative nature of React. You never create your web pages while working with React. You only instruct them. All the React code you write boils down to a single page which hardly has any content and got mostly JavaScript. Hence, the crawler finds very little or no content to index, hampering the overall ranking of the web app.</p><h3><strong>Workaround:</strong></h3><p>Solution to the SEO problem is Server Side Rendering. With server-side rendering, browsers and crawlers get HTML files with all the content hence they can properly index the page.</p><p>Server-side rendering is the easiest way to create an SEO-friendly React website. However, if you want to create an SPA that will render on the server, you’ll need to add an additional layer of <a href="https://nextjs.org/">Next.js</a>.</p><h3><strong>Conclusion:</strong></h3><p>React has evolved and reached a level in which it is highly mature and popular. Testing a React app is much easier compared to any other library or framework. If you are an organisation with great vision for your product, React is a must have for you.</p><p>If you like the article do share it in your Twitter or LinkedIn.</p><p>Find me on Github link below.</p><p><a href="https://github.com/Gaurav2048">Gaurav2048 - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a876aade9ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/why-react-should-be-your-choice-for-web-application-development-2a876aade9ed">Why React should be your choice for web application development.</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>