<?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 Souvik Paul on Medium]]></title>
        <description><![CDATA[Stories by Souvik Paul on Medium]]></description>
        <link>https://medium.com/@souvikpl?source=rss-874757c45e99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yeEjjl-B1dfbT7kSdxr2aw.png</url>
            <title>Stories by Souvik Paul on Medium</title>
            <link>https://medium.com/@souvikpl?source=rss-874757c45e99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:07:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@souvikpl/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[What I Learned While Building Token-Based Authentication]]></title>
            <link>https://javascript.plainenglish.io/what-i-learned-while-building-token-based-authentication-a263ff6869f9?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a263ff6869f9</guid>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[token-based-auth]]></category>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 09:54:29 GMT</pubDate>
            <atom:updated>2025-12-09T13:25:53.871Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently got the opportunity to improve the authentication flow of a web application after it went through a formal security review. The app has a very small user base and was intentionally designed with a simple access model — any authenticated user can access all protected APIs, and there is no need for role-based access control in its current or future scope. Because of this simplicity, the initial implementation relied on a basic JWT-based setup with minimal session handling. However, the security review pointed out several gaps in this approach, especially around token lifetime and session invalidation. That assessment became the trigger for rethinking the authentication strategy and eventually led to implementing a more secure and reliable access-token and refresh-token mechanism.</p><h3>Background: How Authentication Worked Before the Change</h3><p>Before introducing access tokens and refresh tokens, the application followed a very simple authentication flow. Once a user successfully signed in or signed up, the server generated a JWT and set it in the browser’s cookies. This same JWT was then sent to the server with every API request.</p><p>On the backend, all protected routes used a middleware that extracted the JWT from the request cookies, validated it, and allowed the request to proceed only if the token was valid. If validation failed, the server returned a <strong>401 Unauthorized</strong>, and the frontend logged the user out.</p><p>This approach provided basic authentication, but it lacked several essential security features.</p><h3>Problems Found During VAPT</h3><p>During the <strong>Vulnerability Assessment and Penetration Testing (VAPT)</strong>, several issues were identified. These findings made it clear that the current authentication flow needed to be redesigned.</p><ol><li><strong>Excessive JWT Token Lifetime<br></strong>The JWT had an unnecessarily long expiration time (30 days), increasing the window of opportunity for misuse if the token were compromised.<br><strong>VAPT Recommendation:<br>- </strong>Reduce the token lifetime to just a few hours.<br>- Implement a <strong>refresh token mechanism</strong> to securely extend sessions without forcing the user to sign in repeatedly.</li><li><strong>Session Does Not Expire on Logout or Password Change<br></strong>Logging out on the frontend simply cleared the cookie, but the server-side session (i.e., the JWT itself) remained valid until expiry.<br>Similarly, when a user changed their password, existing sessions/tokens were not invalidated.<br><strong>VAPT Recommendation:<br>- </strong>Actively invalidate session tokens on logout or password change.</li></ol><p>If an attacker obtained a user’s JWT, they would retain full access to all protected resources for the entire 30-day validity window. This represents a significant security risk because a compromised token would enable unauthorized access to the application, with no server-side mechanism to revoke or terminate the session.</p><h3>Investigation and Findings</h3><h4><strong>Problem with Short-Lived Access Tokens</strong></h4><p>Short-lived access tokens significantly strengthen security by limiting the window in which a stolen token can be misused. However, they come with an obvious trade-off: once the access token expires, the user must authenticate again to obtain a new one. If this happens too frequently, it can degrade the user experience and make the application feel inconvenient or frustrating — even if the intention is to protect user data. Striking the right balance between security and usability becomes a challenge.</p><h4>Refresh Token to the Rescue</h4><p>This is where refresh tokens help. A refresh token typically has a longer lifetime and can be used to obtain new access tokens without requiring the user to re-enter credentials. When the access token expires, the application silently exchanges the refresh token for a new pair, keeping the session alive without interrupting the user. This behavior is known as <strong>silent authentication</strong>, and it provides a smooth experience while still adhering to best-practice security patterns.</p><h4>Refresh Token Rotation</h4><p>Refresh Token Rotation enhances this further. In this approach, every time the client exchanges a refresh token for new credentials, the server issues a <strong>new</strong> refresh token and invalidates the previous one. This eliminates the idea of a long-lived static refresh token. Even if a refresh token is compromised, its window of usability is extremely small because tokens are continually rotated and previous ones are invalidated immediately. This significantly reduces the risk of replay attacks or prolonged unauthorized access.</p><h4>Problem with Refresh Token Rotation</h4><p>However, rotating refresh tokens introduces another subtle issue. If the user remains logged in and continues exchanging valid refresh tokens, they effectively keep extending the session indefinitely. Each refresh request issues a new RT with a fresh expiration time, and the cycle continues. This creates a scenario where a user may never have to re-authenticate again. This results in <strong>continuous opportunity</strong> for compromise, as the refresh token never naturally expires unless manually revoked.</p><h3>Implementation Details</h3><p>Based on the findings and design considerations, we finalized the following approach:</p><ol><li><strong>Issuing Access and Refresh Tokens<br></strong>When a user logs in or signs up, the server issues two tokens and sets them in HTTP-only cookies:<br>- <strong>Access Token (AT)</strong> with a <strong>60-minute</strong> expiration<br>- <strong>Refresh Token (RT)</strong> with a <strong>30-day</strong> expiration<br>This ensures that each session starts with both a short-lived AT for security and a long-lived RT for silent authentication.</li><li><strong>Handling Access Token Expiry<br></strong>Once the 60-minute AT expires, any request to a protected API will result in a <strong>401 Unauthorized</strong> response.<br>The frontend intercepts these responses, queues all failed API calls, and triggers a call to the <strong>refresh token endpoint</strong>, sending the RT (from the cookie) to obtain a new token pair.<br>When the refresh token API is called:<br>- A <strong>new Access Token</strong> and a <strong>new Refresh Token</strong> are issued.<br>- The <strong>previous RT is revoked</strong> immediately to support rotation.<br>- The new AT again has a <strong>60-minute</strong> expiry.<br>- The new RT does <em>not</em> reset to a fresh 30-day window. Instead, its expiry becomes: <strong>30 days − time already elapsed. </strong>This prevents sliding expiration and ensures the user is required to re-authenticate after the fixed 30-day maximum.</li><li><strong>Session Validation<br></strong>For additional safety, the server maintains a mapping of valid refresh tokens. Each Access Token must correspond to a currently valid Refresh Token entry in the server.<br>If the associated RT is missing, expired, or revoked, the server will return <strong>401 Unauthorized</strong>, preventing access even if the AT itself appears valid.</li></ol><h4>API Implementation Details</h4><ol><li><strong>/login and </strong><strong>/register Endpoints</strong></li></ol><p>The /login and /register routes are responsible for handling user authentication and account creation. As part of their response, the server generates both an <strong>Access Token (AT)</strong> and a <strong>Refresh Token (RT)</strong>. These tokens are standard JWTs containing the following claims:</p><ul><li><strong>user_id</strong> – Identifies the user to whom the token belongs.</li><li><strong>session_id</strong> – A unique UUID created for each login session. This allows a single user to maintain multiple active sessions across different browsers or devices.</li></ul><p>Both tokens also include their respective <strong>expiry timestamps</strong> embedded within the JWT payload.</p><p>After generating the tokens, the server stores the RT inside a Redis cache. This acts as the authoritative source of truth for determining whether a refresh token is valid or revoked.</p><p><strong>Why Redis?</strong></p><p>Redis was chosen for several reasons:</p><ul><li>Low Latency: Redis operates in-memory and provides extremely fast read/write operations — suitable for validating tokens on every refresh request.</li><li>Auto-Expiration Support: The built-in EX attribute lets us associate each token with its TTL. This ensures refresh tokens expire naturally and are removed automatically without manual cleanup.</li><li>Easy Revocation: Since AT validity depends on the presence of a matching RT in Redis, revoking a session becomes as simple as deleting the corresponding Redis key.</li></ul><p><strong>Setting Tokens as HTTP-Only Cookies</strong></p><p>Both the AT and RT are sent back to the browser as secure, HTTP-only cookies. The server sets them as follows:</p><pre>response.set_cookie(<br>    &quot;access_token&quot;,<br>    access_token,<br>    domain=&quot;.server.com&quot;,<br>    httponly=True,<br>    max_age=access_token_expiry,   # matches JWT expiry<br>    samesite=&quot;Strict&quot;,<br>    secure=True,<br>)<br><br>response.set_cookie(<br>    &quot;refresh_token&quot;,<br>    refresh_token,<br>    domain=&quot;.server.com&quot;,<br>    httponly=True,<br>    max_age=refresh_token_expiry,  # matches JWT expiry<br>    samesite=&quot;Strict&quot;,<br>    secure=True,<br>    path=&quot;/refreshToken&quot;,  # Sent only when hitting this endpoint<br>)</pre><p>Cookie Configuration Details:<br>- <strong>httponly=True</strong> prevents JavaScript access, mitigating XSS-based token theft.<br>- <strong>secure=True</strong> ensures cookies are only transmitted over HTTPS.<br>- <strong>samesite=&quot;Strict&quot;</strong> protects against CSRF by blocking cross-site cookie usage.<br>- <strong>path=&quot;/refreshToken&quot;</strong> restricts the RT cookie to only be sent when calling the refresh-token endpoint, reducing exposure.</p><p>2. <strong>/protected-resource</strong></p><p>All protected routes are secured using middleware that intercepts incoming requests before they reach the actual handler. The middleware enforces multiple layers of validation to ensure that both the access token and the corresponding session are legitimate.</p><p><strong>Step 1 (Validate the Access Token (AT)): </strong>The middleware begins by extracting the Access Token from the incoming request cookies. It then attempts to decode and verify the JWT to check if token is expired. If so, the server immediately returns <strong>401 Unauthorized</strong>.</p><p><strong>Step 2 (Verify Session Against Redis): </strong>If the AT is valid, the middleware extracts the user_id and session_id from the token payload. Using these values, it checks Redis to verify that a corresponding refresh token (RT) entry exists. If not, the server again returns <strong>401 Unauthorized</strong>, even if the AT itself is still within its expiry window.</p><p>This layered validation ensures that session integrity is maintained at all times and that access tokens cannot be used beyond the lifetime or validity of their associated refresh tokens.</p><p>3. <strong>/logout</strong></p><p>When a user logs out, the server performs two key actions to fully terminate the session:<br>- <strong>Invalidate the Refresh Token:</strong> Using the user_id and session_id from the Access Token, the server locates the corresponding Redis key and deletes it. This immediately revokes the session at the backend level.<br>- <strong>Clear Authentication Cookies:</strong> The server removes both the Access Token and Refresh Token cookies from the browser.<br>This combination guarantees that the session is invalidated both on the client and the server.</p><p>4. <strong>/resetPassword</strong></p><p>A successful password reset is treated as a high-sensitivity event. To maintain security, <strong>all active sessions for the user must be terminated immediately</strong>. The server achieves this by deleting <strong>all refresh tokens stored in Redis</strong> for the given user. This forces the user to re-authenticate across all devices and browsers, ensuring no compromised session remains valid after a password change.</p><p>5. <strong>/refreshToken</strong></p><p>This endpoint handles generating a new Access Token (AT) and Refresh Token (RT). The client is expected to send the refresh token via a cookie named <strong>refresh_token</strong>.</p><p><strong>Step 1 (Decode and Validate the RT (JWT)): </strong>Extract user_id, session_id, and other metadata. If decoding fails or the token is malformed → <strong>401 Unauthorized</strong>.</p><p><strong>Step 2 (Verify RT Against Redis): </strong>The server checks whether a matching RT exists in Redis. If the key is missing or expired → <strong>401 Unauthorized</strong>.</p><p><strong>Step 3 (Issue New Token Pair): </strong>If validation succeeds, A <strong>new Access Token</strong> with a fresh 60-minute expiry is generated. A <strong>new Refresh Token</strong> is issued as well, but its expiration is adjusted.</p><p><strong>Step 4 (Revoke Previous RT): </strong>The old RT entry in Redis is deleted, and the new RT is written with its updated TTL.</p><p>This maintains refresh token rotation while enforcing a hard upper limit on session longevity.</p><h3>Conclusion</h3><p>Building a secure authentication flow involves balancing usability, performance, and robust security checks. The approach described here is one effective way to handle access tokens, refresh tokens, and session validation — but it’s certainly not the only one. Every system has its own constraints, and there’s always room to refine or rethink parts of the design.</p><p>If you have suggestions, alternative ideas, or critical feedback that can make this approach more solid, I’d love to hear them. Feel free to share your thoughts in the comments or reach out — constructive criticism is always welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a263ff6869f9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/what-i-learned-while-building-token-based-authentication-a263ff6869f9">What I Learned While Building Token-Based Authentication</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Analytics Dashboard Frontend: Decisions, Challenges, and Takeaways]]></title>
            <link>https://levelup.gitconnected.com/building-an-analytics-dashboard-frontend-decisions-challenges-and-takeaways-88561db9043f?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/88561db9043f</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 12:01:17 GMT</pubDate>
            <atom:updated>2025-12-08T03:08:12.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*matagJ8hxcFflS9b" /><figcaption>Photo by <a href="https://unsplash.com/@justin_morgan?utm_source=medium&amp;utm_medium=referral">Justin Morgan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Building an analytics dashboard is one of those tasks that appears straightforward on the surface — until you start implementing it. Recently, I worked on a module where a single page needed to present complex financial analytics data in <strong>textual</strong>, <strong>tabular</strong>, and <strong>graphical</strong> formats. What made it challenging wasn’t just the volume of data, but the number of combinations, filters, aggregations, and drill-down requirements the UI needed to support.</p><p>In this article, I’ll walk through how I approached these challenges, the architectural choices I made, pitfalls I encountered, and lessons that helped me deliver the feature.</p><p>Although the actual dashboard I built dealt with financial metrics, I’m using user analytics here as an easier-to-relate example.</p><p>Before diving into the solution and thought process, here’s the full set of requirements.</p><h3>Requirements</h3><p>The application needed an analytics dashboard that could display user-related metrics in <strong>text</strong>, <strong>tables</strong>, and <strong>interactive graphs</strong>. The dashboard should allow users to analyze how many users <strong>signed up</strong>, <strong>churned</strong>, or are <strong>active</strong>, across various time and region-based filters.</p><ol><li><strong>Basic Metrics by Time Period</strong><br>Display total numbers for:<br>- Signups<br>- Churned users<br>- Active users<br>Across time ranges:<br>- This week / Last week<br>- This month / Last month<br>- This quarter / Last quarter<br>- This year / Last year<br>- Any custom date range</li><li><strong>Region-Based Metrics</strong><br>Show the same metrics (signups / churn / active) segmented by North / South / East / West / Central</li><li><strong>Time-Based + Granular Breakdowns</strong><br>Support breakdowns by:<br>- Day-wise<br>- Week-wise<br>- Month-wise<br>- Year-wise<br>For: This week / Last week / This month / Last month / This quarter / Last quarter / This year / Last year / Any custom date range</li><li><strong>Region-Based + Time-Based Combined<br></strong>Allow combinations like:<br>- Time period + Region-wise<br>- Region + Day-wise / Week-wise / Month-wise / Year-wise<br>Examples:<br>- Total signups this month, split region-wise<br>- Churned users in the North region, month-wise<br>- Active users this quarter, shown week-wise and region-wise</li><li><strong>Drill-Down Interactions<br></strong>When visualising day/week/month/quarter/year-wise data, allow users to click on a specific time unit and view:<br>- Region-wise split for that selected day/week/month/quarter/year</li></ol><h3>Initial UI Sketch</h3><p>To set the context visually, here’s a rough sketch that outlines how the analytics dashboard was initially imagined in terms of layout and information flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1Rdro-2w-fVdvNakBc2cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVlIcQu6K1V_6EjgIsytgQ.png" /></figure><h3>Charting Library Selection</h3><p>Given the volume of metrics, filters, and split combinations, it was clear early on that the dashboard would require multiple types of visualizations — <strong>bar charts, stacked bar charts, multi-bar charts, area charts, and stacked area charts</strong>.<br> Additionally, <strong>bar and stacked bar charts needed to toggle into area and stacked area views</strong> to offer better visual clarity depending on the dataset.</p><p>The following use cases help clarify why these specific chart types were necessary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njUT_Fjhm4nFj4IAqvI2dA.png" /></figure><p>There are several charting libraries available in the React ecosystem, but I chose <strong>shadcn charts</strong> for the following reasons:</p><ul><li><strong>Seamless integration with our existing UI system<br></strong>Our frontend already uses shadcn for components, so adopting its charting suite kept the design consistent and reduced integration overhead.</li><li><strong>Highly composable React components<br></strong>Shadcn exposes individual SVG elements — each bar, line, and area — as standalone React components. This makes it easy to attach event listeners and enables intuitive <strong>drill-down interactions</strong>, since the chart behaves like a compound component.</li><li><strong>Built on SVG for superior scalability<br></strong>Because the charts are rendered as SVGs, they scale cleanly without pixelation on both small and large screens, ensuring crisp visuals across devices.</li></ul><p>This combination of flexibility, composability, and consistency made shadcn charts the most suitable choice for the dashboard.</p><p>Once the feature went live, we started noticing that the application froze whenever the charts attempted to render <strong>large datasets</strong>. This is because SVG-Based chart libraries struggle with large data. SVG is <strong>DOM-based</strong>, meaning every bar, point, line segment, or area becomes an individual DOM node. When the dataset grows — say hundreds or thousands of points — this leads to:</p><ul><li>Huge number of DOM elements</li><li>Expensive layout and paint operations</li><li>Large memory consumption</li><li>Freezing or crashing of the browser’s main thread</li></ul><p>SVG is excellent for small to medium datasets, but it simply doesn’t scale well for high-density data visualisation.</p><p><strong>What We Realized (a bit late):</strong></p><ul><li>Choosing an SVG-based library for analytics with large data volumes was a mistake we only recognized after real-world usage.</li><li>Rewriting the entire charting module with a new library would have required significant effort, refactoring, and retesting.</li></ul><p><strong>Our Practical Fix:</strong></p><p>To avoid re-implementing charts from scratch, we decided to i<strong>mpose limits on how much data can be visualized at once </strong>(e.g., restricting date ranges, capping the number of data points, etc.). This workaround ensured the dashboard stayed usable without major rewrites.</p><p><strong>Canvas-Based Chart Libraries as an Alternative:</strong></p><p>Canvas renders graphics using a <strong>pixel-based drawing API</strong> instead of creating individual DOM nodes. This makes it significantly more efficient when dealing with hundreds or thousands of data points.<br>Why Canvas Scales Better:<br>- No DOM nodes → far lower memory consumption<br>- Faster draw operations<br>- Smoother rendering for large datasets<br>- No layout or reflow calculations</p><h3>Defining data model</h3><p>Designing the data model for an analytics dashboard revolves around two core aspects:</p><ol><li>Understanding how metrics, filters, and splits translate into database queries</li><li>Structuring the API response in a format your chart library can directly consume</li></ol><p>Let’s focus on the first point.</p><p>To design a scalable analytics system, you must first understand how every user-selected combination — metrics, filters, date ranges, regions, and splits — maps to a SQL query.</p><p>Consider the basic MySQL pattern:</p><pre>SELECT <br>    column_to_group_by, <br>    SUM(column_to_sum) AS sum_alias<br>FROM <br>    table_name<br>WHERE <br>    condition1 AND condition2<br>GROUP BY <br>    column_to_group_by</pre><p>This structure directly mirrors how an analytics dashboard thinks:<br>- <strong>SELECT</strong> → The metrics we want (e.g., signups, churn, active users)<br>- <strong>WHERE</strong> → The filters applied (date range, region, status, etc.)<br>- <strong>GROUP BY</strong> → The splits we need (time, region)</p><p>Now, let’s discuss the second point.</p><p>When evaluating the shadcn chart components, I noticed an important advantage: <strong>all chart types — bar, stacked bar, area, stacked area — consume the same underlying data model.</strong><br>This significantly simplified both the API design and the backend logic.</p><p>Since every chart type expects data in a uniform structure, it became clear that:<br>- The backend only needs <strong>one analytics API.<br>- </strong>This API accepts a combination of <strong>metrics, filters, and splits.<br>- </strong>It returns data in a <strong>single, consistent model</strong>, regardless of which chart will use it.<br>- Along with the data, the backend also tells the frontend <strong>which chart type to render.</strong></p><p>The choice of chart depends entirely on what the user is analyzing:<br>- Time-based comparisons → Bar or Area<br>- Region-wise breakdowns → Stacked Bar or Stacked Area<br>- Multi-metric comparisons → Multi-bar</p><h3>Frontend Design</h3><p>Since this was the first time an analytics page was being introduced in the application, my priority was to keep the architecture simple, clear, and easy to extend later. With that in mind, here’s how I structured the <strong>Analytics Page</strong> component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mw4QuYwZNKDKAa-Z7YpB5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FLGkPyvDn6CHawXwvvQJw.png" /></figure><p><strong>&lt;AnalyticsContextProvider/&gt;<br></strong>This component manages the <strong>entire state</strong> of the analytics page using the React Context API. It listens for changes in the &lt;AnalyticsControlPanel /&gt;, and whenever the user updates any control—metrics, filters, or splits—it makes an API call to fetch the relevant analytics data. Once the response arrives, it triggers an update in the &lt;AnalyticsRenderer /&gt; to re-render the visualisation.</p><p><strong>&lt;AnalyticsControlPanel/&gt;<br></strong>This component includes all user-facing controls that determine <em>what</em> data should be shown. It lets users choose combinations of <strong>metrics</strong>, <strong>date filters</strong>, <strong>region filters</strong>, and <strong>split options</strong>. Any change here is immediately reflected in the context provider, prompting a new analytics fetch.</p><p><strong>&lt;AnalyticsRenderer/&gt;<br></strong>This component is responsible for displaying the fetched analytics data in different formats — textual, tabular, or graphical. The API response includes a field that specifies <strong>which visualization format</strong> should be used, and the renderer switches to the appropriate component accordingly.<br><strong>Supported Visualization Components:<br>1. &lt;Number /&gt;</strong>: Displays only numeric insights — such as total signups or total churn — for a selected date range and filter combination. No chart is rendered when no split is applied.<br><strong>2. &lt;BarGraph /&gt;</strong>: Renders both <strong>bar graphs</strong> and <strong>stacked bar graphs</strong>. When drill-down is allowed, individual bars become clickable; clicking a bar updates the control panel values and triggers a new analytics fetch.<br><strong>3. &lt;AreaGraph /&gt;</strong>: Renders <strong>area graphs</strong> and <strong>stacked area graphs</strong>. Similar to bar graphs, certain areas are interactive and support drill-down actions.<br><strong>4. &lt;MultiBarGraph /&gt;</strong>: Used when multiple metrics are selected along with exactly one split. Displays multiple adjacent bars for each point on the x-axis.<br><strong>5. &lt;AnalyticsRawData /&gt;</strong>: Shows the underlying dataset — used for the charts — in a tabular format. Users can view this by toggling a switch.</p><p><strong>&lt;AnalyticsActions/&gt;<br></strong>This component contains additional actions that operate on the analytics result set. It includes features such as:<br>- Toggling between <strong>normal</strong> and <strong>cumulative</strong> data<br>- Export to Excel<strong><br>- </strong>Any future analytics-level operations</p><h3>Conclusion</h3><p>Building this analytics dashboard was a deep dive into handling complex data combinations, managing performance constraints, and designing a frontend architecture that can grow as business needs evolve. The approach I took — centralized state management, a unified API contract, and modular visualization components — worked well for the scale and constraints of the project at that time. But like any engineering solution, it isn’t the only way, nor is it perfect.</p><p>There are areas where decisions could have been different, especially around charting libraries and performance optimizations. With evolving requirements, larger datasets, or different infrastructure constraints, an entirely different strategy might be more suitable. And that’s the beauty of system design — there’s always room for improvement, iteration, and learning from what worked and what didn’t.</p><p>If you’re building something similar, I hope this breakdown gives you a practical starting point, but also encourages you to question, adapt, and refine your own approach. Analytics systems grow quickly, and the “best” design is always the one that evolves with your product, your team, and your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88561db9043f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-an-analytics-dashboard-frontend-decisions-challenges-and-takeaways-88561db9043f">Building an Analytics Dashboard Frontend: Decisions, Challenges, and Takeaways</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[Responsive Images: A Comprehensive Guide to Handling Images in Web Apps]]></title>
            <link>https://levelup.gitconnected.com/responsive-images-a-comprehensive-guide-to-handling-images-in-web-apps-2a2ee839e7b8?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a2ee839e7b8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[responsive-images]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 14:45:45 GMT</pubDate>
            <atom:updated>2024-12-27T01:58:40.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrI8PSzd7s-OXz97DAKdKQ.png" /></figure><p>In today’s web development landscape, delivering responsive and optimized media is critical for a seamless user experience. Whether you’re dealing with images or videos, using the right tools and techniques can greatly improve performance and visual fidelity. This guide explores how to display images in the UI.</p><h3>Displaying Images: Choosing Between &lt;img&gt; with `srcset` and &lt;picture&gt;</h3><p>Choosing the right HTML element for displaying images depends on your requirements. Let’s break down the scenarios and use cases for the &lt;img&gt; tag with srcset and the &lt;picture&gt; element.</p><h4>1. When to Use &lt;img&gt; with `srcset`</h4><p>The &lt;img&gt; tag with the srcset attribute is ideal when the same image content needs to be displayed in different resolutions for responsive design or high-DPI (High Dots Per Inch / Retina displays) screens.</p><pre>&lt;img<br>  src=&quot;https://picsum.photos/id/10/480/320&quot;<br>  srcset=&quot;<br>      https://picsum.photos/id/10/480/320 480w,<br>      https://picsum.photos/id/10/800/533 800w,<br>      https://picsum.photos/id/10/1200/800 1200w&quot;<br>  sizes=&quot;(max-width: 600px) 480px,<br>         (max-width: 1200px) 800px,<br>         1200px&quot;<br>  alt=&quot;A beautiful image&quot;<br>&gt;</pre><p>Here:</p><ul><li>srcset specifies the available image files and their widths.</li><li>sizes helps the browser choose the most appropriate image based on the viewport width.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KwjAY0aFz42jKqRgzvcQdg.gif" /></figure><p>Check out the code <a href="https://github.com/souvik-pl/Responsive_images_and_videos/tree/master/img_with_srcset">here</a>.</p><h4>2. When to Use &lt;picture&gt; with &lt;source&gt;</h4><p>The &lt;picture&gt; element is more versatile and supports art direction, making it perfect for scenarios where:</p><ul><li>The content (e.g., crop or composition) changes based on the device or layout.</li><li>Different image formats (e.g., WebP, AVIF, JPEG) are required.</li></ul><p><strong>Art direction</strong> refers to the practice of tailoring the visual presentation of content, such as images or videos, to suit the context or medium in which it is displayed. In web design, this often involves delivering different versions of an image or video depending on the screen size, orientation, or other factors, ensuring that the content not only fits but also enhances the user experience.</p><p><strong>Use Case 1</strong>: Different Images for Mobile and Desktop</p><pre>&lt;picture&gt;<br>  &lt;source<br>    srcset=&quot;https://picsum.photos/id/10/800/400&quot;<br>    media=&quot;(min-width: 800px)&quot;<br>    alt=&quot;Landscape orientation for desktop&quot;<br>  /&gt;<br>  &lt;source<br>    srcset=&quot;https://picsum.photos/id/10/400/600&quot;<br>    media=&quot;(min-width: 400px)&quot;<br>    alt=&quot;Portrait orientation for tablet&quot;<br>  /&gt;<br>  &lt;img<br>    src=&quot;https://picsum.photos/id/10/300/300&quot;<br>    alt=&quot;Square format for mobile&quot;<br>    class=&quot;responsive-img&quot;<br>  /&gt;<br>&lt;/picture&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AwXCoE8c-VDjhQUJhIyQHA.gif" /></figure><p>Check out the code <a href="https://github.com/souvik-pl/Responsive_images_and_videos/tree/master/picture_source_1">here</a>.</p><p><strong>Use Case 2</strong>: Optimized Formats with Fallbacks</p><p>Here, we have used different images (with IDs 10, 11, and 12) to make it easier to identify which image has been loaded.</p><pre>&lt;picture&gt;<br>  &lt;source<br>    srcset=&quot;https://picsum.photos/id/10/600/400.webp&quot;<br>    type=&quot;image/webp&quot;<br>  /&gt;<br>  &lt;source<br>    srcset=&quot;https://picsum.photos/id/11/600/400.jpg&quot;<br>    type=&quot;image/jpeg&quot;<br>  /&gt;<br>  &lt;img<br>    src=&quot;https://picsum.photos/id/12/600/400.jpg&quot;<br>    alt=&quot;Fallback image&quot;<br>  /&gt;<br>&lt;/picture&gt;</pre><p>Check out the code <a href="https://github.com/souvik-pl/Responsive_images_and_videos/tree/master/picture_source_2">here</a>.</p><h4>3. Using &lt;picture&gt;, &lt;source&gt; and `srcset` together</h4><p>For maximum flexibility and optimization, you can combine the &lt;picture&gt; element with &lt;source&gt; for art direction and format support, and the srcset for responsive resolutions. This approach allows you to deliver the most suitable image format (e.g., WebP or JPEG) while ensuring the device&#39;s best resolution. This hybrid method offers a comprehensive solution for modern web design.</p><pre>&lt;picture&gt;<br>  &lt;!--Here we have taken a different images (id = 10, 11, 12). So that it is easier to know which image is loaded--&gt;<br>  &lt;source<br>    srcset=&quot;<br>      https://picsum.photos/id/10/480/320.webp 480w<br>      https://picsum.photos/id/10/800/533.webp 800w,<br>      https://picsum.photos/id/10/1200/800.webp 1200w<br>    &quot;<br>    sizes=&quot;(max-width: 600px) 480px,<br>          (max-width: 1200px) 800px,<br>          1200px&quot;<br>    type=&quot;image/webp&quot;<br>  /&gt;<br>  &lt;source<br>    srcset=&quot;<br>      https://picsum.photos/id/11/480/320.jpg 480w<br>      https://picsum.photos/id/11/800/533.jpg 800w,<br>      https://picsum.photos/id/11/1200/800.jpg 1200w<br>    &quot;<br>    sizes=&quot;(max-width: 600px) 480px,<br>           (max-width: 1200px) 800px,<br>           1200px&quot;<br>    type=&quot;image/jpeg&quot;<br>  /&gt;<br>  &lt;img<br>    src=&quot;https://picsum.photos/id/12/480/320.jpg&quot;<br>    srcset=&quot;<br>      https://picsum.photos/id/12/480/320.jpg 480w<br>      https://picsum.photos/id/12/800/533.jpg 800w,<br>      https://picsum.photos/id/12/1200/800.jpg 1200w<br>    &quot;<br>    sizes=&quot;(max-width: 600px) 480px,<br>           (max-width: 1200px) 800px,<br>           1200px&quot;<br>    alt=&quot;Fallback image&quot;<br>  /&gt;<br>&lt;/picture&gt;</pre><p>Check out the code <a href="https://github.com/souvik-pl/Responsive_images_and_videos/tree/master/picture_source_srcset">here</a>.</p><p>Art direction is a crucial aspect of modern web design, going beyond simple responsiveness to ensure that image content is meaningful, visually compelling, and tailored to the context in which it is displayed. By leveraging tools like the &lt;picture&gt; element, designers and developers can create an experience that truly resonates with users across all devices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a2ee839e7b8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/responsive-images-a-comprehensive-guide-to-handling-images-in-web-apps-2a2ee839e7b8">Responsive Images: A Comprehensive Guide to Handling Images in Web Apps</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[Building a Skeleton Loader Library for React]]></title>
            <link>https://levelup.gitconnected.com/building-a-skeleton-loader-library-for-react-2cf680c236ee?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf680c236ee</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[shimmer]]></category>
            <category><![CDATA[react-libraries]]></category>
            <category><![CDATA[shimmer-loading]]></category>
            <category><![CDATA[skeleton-loaders]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 11:15:12 GMT</pubDate>
            <atom:updated>2024-06-23T13:04:14.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xo6jTZ_lmY67_pVe" /><figcaption>Photo by <a href="https://unsplash.com/@mike_van_den_bos?utm_source=medium&amp;utm_medium=referral">Mike van den Bos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the fast-evolving world of web development, UI component libraries have become invaluable tools for developers. These libraries, such as <a href="https://mui.com/">Material-UI</a>, <a href="https://v2.chakra-ui.com/">Chakra UI</a>, <a href="https://ant.design/">Ant Design</a>, and <a href="https://ui.shadcn.com/">ShadCN</a>, offer a vast array of pre-built components, enabling rapid and consistent development of user interfaces. They enhance productivity, ensure design consistency, and allow developers to focus on the unique aspects of their applications rather than reinventing the wheel. However, sometimes, the focus needs to be more specific to meet certain performance or design requirements. In this article, I introduce <a href="https://github.com/souvik-pl/skeleton-loader-react">@paul/skeleton-loader-react</a>, a lightweight skeleton loader component library for React. Unlike comprehensive UI libraries, this project focuses on offering a simple but effective skeleton loader to enhance the user experience while data is loading.</p><p><a href="https://github.com/souvik-pl/skeleton-loader-react">GitHub - souvik-pl/skeleton-loader-react</a></p><h4>Key Considerations in Developing this Library</h4><p>While developing the <a href="https://github.com/souvik-pl/skeleton-loader-react">@paul/skeleton-loader-react</a> library, several important factors were taken into account to ensure its effectiveness and ease of use:</p><ol><li><strong>Skeleton Loader Variants</strong>:<br>The library supports three types of skeleton loaders: circular, rectangular, and rectangular with rounded corners.</li><li><strong>Single Component Exposure</strong>:<br>The library exposes only one component, &lt;Skeleton /&gt;, simplifying the API and usage.</li><li><strong>Variant Prop</strong>:<br>The variant prop in &lt;Skeleton /&gt; determines the type of skeleton loader (circular, rectangular, or rectangular with rounded corners).</li><li><strong>Variant-Specific Props</strong>:<br>Depending on the selected variant, the props for &lt;Skeleton /&gt; will change. For example, the borderRadius prop is applicable only for the rectangular variant with rounded corners, not for the plain rectangular variant.</li><li><strong>TypeScript Integration</strong>:<br>Using TypeScript allows developers to benefit from auto-suggestions and hints about the props for each variant, making development more intuitive and reducing the likelihood of errors.</li><li><strong>Compatibility with Various Project Setups</strong>:<br>The library is configured to be easily used with projects created using Create React App (CRA), Vite, and other common React project setups.</li><li><strong>Reusable Boilerplate Code</strong>:<br>The codebase of <a href="https://github.com/souvik-pl/skeleton-loader-react">@paul/skeleton-loader-react</a> can serve as a boilerplate for developers who wish to create their own React libraries. By removing the contents of the src folder, developers can use the existing setup to build their own custom components or libraries.</li></ol><h4>Preview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*hI-zSabP8khblMCEM9QDJg.png" /></figure><h4>Installation</h4><p>Install the library using npm:</p><pre>npm install https://github.com/souvik-pl/skeleton-loader-react.git</pre><h4>Usage</h4><pre>import React from &quot;react&quot;;<br>import { Skeleton } from &quot;@paul/skeleton-loader-react&quot;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Circle Skeleton&lt;/h2&gt;<br>      &lt;Skeleton variant=&quot;circle&quot; height=&quot;100px&quot; width=&quot;100px&quot; animated={true} /&gt;<br><br>      &lt;h2&gt;Rectangle Skeleton&lt;/h2&gt;<br>      &lt;Skeleton variant=&quot;rectangle&quot; height=&quot;100px&quot; width=&quot;50vw&quot; animated={true} /&gt;<br><br>      &lt;h2&gt;Rectangle Rounded Skeleton&lt;/h2&gt;<br>      &lt;Skeleton<br>        variant=&quot;rectangle-rounded&quot;<br>        borderRadius=&quot;10px&quot;<br>        width=&quot;50vw&quot;<br>        height=&quot;15px&quot;<br>        animated={true}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h4>Ending Notes</h4><p>I encourage you to try out this library in your project. Feel free to fork the repository and customize it to fit your specific needs or use it as a boilerplate for your own React libraries.</p><p>Contributions are always welcome — whether it’s reporting issues, suggesting features, or submitting pull requests.</p><p>Thank you. Happy coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf680c236ee" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-skeleton-loader-library-for-react-2cf680c236ee">Building a Skeleton Loader Library for React</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[Understanding React’s Render and Commit Phases]]></title>
            <link>https://javascript.plainenglish.io/understanding-reacts-render-and-commit-phases-2cc24b57acca?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc24b57acca</guid>
            <category><![CDATA[react-rendering]]></category>
            <category><![CDATA[useeffect-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[componentdidmount]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 17:42:30 GMT</pubDate>
            <atom:updated>2024-06-13T01:07:37.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FiojxcTkuno5SZFk" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will explore React’s Render and Commit Phases by examining the behaviour of the useEffect hook (for functional components) and the componentDidMount lifecycle method (for class-based components) when a component is rendered for the first time.</p><p>When React renders elements on the UI, it goes through two phases: the Render Phase and the Commit Phase.</p><h4>Render Phase</h4><p>The render phase is when React prepares the changes but does not actually apply them to the DOM. During this phase, React performs the following steps:</p><ol><li>React calls the render method (of the class-based component) or the component function (of the functional component) to compute the next tree of React elements also known as <strong>Virtual DOM</strong>.</li><li>React compares the newly returned tree of React elements with the previous tree to determine what has changed. This process is known as <strong>reconciliation </strong>or <strong>diffing</strong>.</li></ol><h4>Commit Phase</h4><p>The commit phase is when React applies the changes prepared during the render phase to the actual DOM. After committing changes to the DOM, React runs lifecycle methods (like componentDidMount, componentDidUpdate, and componentWillUnmount for class components) and hooks (like useEffect for functional components).</p><p>Now, let’s understand the above concepts with the following use cases —</p><p><strong>Case 1 — For a single component</strong></p><pre>function App() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;App commited&quot;);<br>  }, []);<br><br>  console.log(&quot;App rendered&quot;);<br>  <br>  return (<br>    &lt;div&gt;<br>      App<br>    &lt;/div&gt;<br>  )<br>}</pre><p>When the above code runs for the first time, it will print the following in the console:</p><pre>App rendered<br>App commited</pre><p>By looking at the ordering of the logs, we can understand that first, the App component gets rendered (Render Phase), and then it gets mounted to the DOM (Commit Phase).</p><p>Similar behaviour can be seen in the class-based component as well.</p><pre>class App extends React.Component {<br>  componentDidMount() {<br>    console.log(&quot;App commited&quot;);<br>  }<br><br>  render() {<br>    console.log(&quot;App rendered&quot;);<br>    return &lt;div&gt;App&lt;/div&gt;;<br>  }<br>}</pre><p>Output —</p><pre>App rendered<br>App commited</pre><p><strong>Case 2 — For multiple components</strong></p><pre>function App() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;App commited&quot;);<br>  }, []);<br><br>  console.log(&quot;App rendered&quot;);<br><br>  return (<br>    &lt;div&gt;<br>      App<br>      &lt;Comp1 /&gt;<br>      &lt;Comp2 /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>function Comp1() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Comp1 commited&quot;);<br>  }, []);<br><br>  console.log(&quot;Comp1 rendered&quot;);<br><br>  return &lt;div&gt;Comp1&lt;/div&gt;;<br>}<br><br>function Comp2() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Comp2 commited&quot;);<br>  }, []);<br><br>  console.log(&quot;Comp2 rendered&quot;);<br><br>  return &lt;div&gt;Comp2&lt;/div&gt;;<br>}</pre><p>When the above code runs for the first time, it will print the following in the console:</p><pre>App rendered<br>Comp1 rendered<br>Comp2 rendered<br><strong>Comp1 commited<br>Comp2 commited<br>App commited</strong></pre><p>Here, it is important to note that React traverses each component down the tree and renders all of them one by one initially. Then, it starts committing all of them one by one, starting from the leaf nodes of the tree and moving up to the root.</p><p>The above log demonstrates a clear distinction between the Render Phase and the Commit Phase.</p><p>This is true for class-based components as well.</p><pre>class App extends React.Component {<br>  componentDidMount() {<br>    console.log(&quot;App commited&quot;);<br>  }<br><br>  render() {<br>    console.log(&quot;App rendered&quot;);<br>    return (<br>      &lt;div&gt;<br>        App<br>        &lt;Comp1 /&gt;<br>        &lt;Comp2 /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>class Comp1 extends React.Component {<br>  componentDidMount() {<br>    console.log(&quot;Comp1 commited&quot;);<br>  }<br><br>  render() {<br>    console.log(&quot;Comp1 rendered&quot;);<br>    return &lt;div&gt;Comp1&lt;/div&gt;;<br>  }<br>}<br><br>class Comp2 extends React.Component {<br>  componentDidMount() {<br>    console.log(&quot;Comp2 commited&quot;);<br>  }<br><br>  render() {<br>    console.log(&quot;Comp2 rendered&quot;);<br>    return &lt;div&gt;Comp2&lt;/div&gt;;<br>  }<br>}</pre><p>Output —</p><pre>App rendered<br>Comp1 rendered<br>Comp2 rendered<br>Comp1 commited<br>Comp2 commited<br>App commited</pre><p>Do visit the following link. It will help you understand the lifecycle methods of React along with Render and Commit Phases diagrammatically —</p><p><a href="https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/">React Lifecycle Methods diagram</a></p><p>Also, if you’d like to explore the code explained above, you can clone the following repository.</p><p><a href="https://github.com/souvik-pl/React_Render_And_Commit_Phases">GitHub - souvik-pl/React_Render_And_Commit_Phases</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc24b57acca" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-reacts-render-and-commit-phases-2cc24b57acca">Understanding React’s Render and Commit Phases</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Custom Redux Store in a React Application]]></title>
            <link>https://javascript.plainenglish.io/implementing-a-custom-redux-store-in-a-react-application-cc4b691acf23?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc4b691acf23</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-store]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 14:49:50 GMT</pubDate>
            <atom:updated>2024-02-26T01:31:00.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8RBnDbsqachM0gfA" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Redux is a popular state management library used in React applications to manage complex states across components. This article will demonstrate how to implement a custom Redux store and use it in a React application. We’ll break down the process into two parts: creating the custom Redux store library and using it in a React application.</p><p>Here is a preview of our application where you can see that upon uploading the profile photo, it gets updated in both places simultaneously. This is happening due to the centralized Redux store. Both the navbar and the profile component are subscribed to that store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHHw2pIHt5StV57E8G9rRQ.gif" /></figure><h4>Part 1: Creating the Custom Redux Store Library</h4><p>The custom Redux store will be created as a separate npm library called redux-lib. This library will expose a createStore() function that creates a Redux store, allowing developers to manage the complete state tree of their app.</p><p>The createStore() function accepts two arguments:</p><ul><li>reducer: A function that determines how the application’s state changes in response to actions sent to the store. The reducer is a pure function that takes the current state and an action as arguments and returns the new state.</li><li>initialState: An optional parameter that represents the initial state of the application. If not provided, the initial state will be undefined.</li></ul><p>The createStore() function returns a Store object, which has the following methods:</p><ul><li>getState(): Returns the current state of the store.</li><li>dispatch(action): Dispatches an action to the store. The action is a plain JavaScript object that must have a type property which indicates the type of action being performed. The store will call the reducer with the current state and the action to calculate the new state.</li><li>subscribe(listener): Adds a change listener to the store. The listener is called whenever the state of the store changes.</li></ul><h4>Part 2: Using the Custom Redux Store into a React Application</h4><p>Once the redux-lib library is created, it can be integrated into a React application (react-app). The React application will use the custom Redux store to manage its state.</p><p>To integrate the custom Redux store into the React application, follow these steps:</p><ol><li>Create a Redux store using the createStore() function from the redux-lib library. Pass the reducer and initial state as arguments to the createStore() function.</li><li>Use the getState(), dispatch(), and subscribe() methods of the Redux store to manage the state of the React application.</li></ol><p>The source code for this project is available in the following repository —</p><p><a href="https://github.com/souvik-pl/Redux_Store_Implementation">GitHub - souvik-pl/Redux_Store_Implementation</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc4b691acf23" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-a-custom-redux-store-in-a-react-application-cc4b691acf23">Implementing a Custom Redux Store in a React Application</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Revealing Module Pattern]]></title>
            <link>https://javascript.plainenglish.io/the-revealing-module-pattern-a670c499b996?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/a670c499b996</guid>
            <category><![CDATA[code-organization]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[revealing-module-pattern]]></category>
            <category><![CDATA[namespacing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 14:05:51 GMT</pubDate>
            <atom:updated>2024-01-12T04:03:18.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D-6UwwloVmyyvBuv" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript, the language of the web, has evolved immensely over the years, yet it grapples with a fundamental challenge — the absence of namespacing. Namespacing is crucial for organizing and encapsulating variables and functions under specific scopes, preventing naming conflicts, and enhancing code structure. In this article, we’ll understand the Revealing Module Pattern, a design pattern that empowers JavaScript developers to create modular and organized code while addressing the challenge of global scope pollution.</p><h4>Understanding the Revealing Module Pattern</h4><p>At its core, the Revealing Module Pattern leverages the concept of an Immediately Invoked Function Expression (IIFE) to encapsulate variables and methods within a local scope. This strategy prevents global scope pollution, enhancing code maintainability and reducing the risk of naming conflicts.</p><pre>const bankAccount = (function () {<br>  // private member<br>  let balance = 2000;<br> <br>  // Private Method (prefixed with underscores)<br>  function _transerMoney () {<br>    //...<br>  }<br><br>  // Public Method<br>  function makePayment () {<br>    _transerMoney();<br>   }<br><br>  return {<br>    makePayment<br>  }<br>})();<br><br>bankAccount.makePayment();</pre><p>In the example above, the Revealing Module Pattern is employed to create a bankAccount module. Within the IIFE, private members like balance and the private method _transerMoney are encapsulated. The public method makePayment is explicitly exposed for external use. This clear distinction between public and private members is facilitated by the principles of closure—local functions retaining access to their parent function&#39;s scope.</p><h4>Advantages of the Revealing Module Pattern</h4><ol><li><strong>Encapsulation:</strong> The pattern promotes encapsulation by encapsulating variables and methods within a local scope, preventing them from leaking into the global scope.</li><li><strong>Code Organization:</strong> With the Revealing Module Pattern, code is organized into modules, making it more modular and maintainable. Each module has a well-defined set of public methods, reducing complexity.</li><li><strong>Preventing Global Scope Pollution:</strong> By restricting access to private members and exposing only essential public methods, the pattern mitigates the risk of global scope pollution and naming conflicts.</li><li><strong>Code Privacy:</strong> The use of closures ensures that private members and methods remain inaccessible from the outside, enhancing code privacy and security.</li></ol><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a670c499b996" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-revealing-module-pattern-a670c499b996">The Revealing Module Pattern</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LRU Cache]]></title>
            <link>https://javascript.plainenglish.io/understanding-lru-cache-b46c48e07e45?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46c48e07e45</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[browser-tabs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 18:42:40 GMT</pubDate>
            <atom:updated>2024-01-11T01:11:36.364Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of web development, managing browser tabs efficiently is a crucial aspect of delivering a seamless user experience. This article explores the creation of a React application that implements browser tabs functionality using an LRU (Least Recently Used) Cache. This approach allows for a space-efficient storage mechanism, ensuring that frequently accessed tab content is readily available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Q31CwsYMCfkG0D9ID6eL9A.png" /></figure><h3>Overview</h3><p>This React app consists of 8 tabs, each representing a specific content section. When a user clicks on a tab, the corresponding content is displayed, offering a responsive and dynamic tabbed browsing experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ab3vrJt4hxjiXRP7Jkx_Q.png" /></figure><h3>LRU Cache in a Nutshell</h3><h4>Definition</h4><p>LRU stands for “Least Recently Used,” and an LRU cache is a data structure that maintains a limited number of items and automatically removes the least recently used item when the capacity is reached. The primary objective is to optimize space utilization by retaining items that are frequently accessed, with the anticipation that recently used items are likely to be used again in the near future.</p><h4>Key Characteristics</h4><ol><li>Capacity: The cache has a fixed capacity, specifying the maximum number of items it can store.</li><li>Access Operations: Each time an item is accessed (read or updated), it becomes the most recently used item. The order of access is tracked.</li><li>Eviction: When the cache reaches its capacity and a new item needs to be added, the least recently used item is evicted to make space for the newcomer.</li></ol><h3>LRUCache Class</h3><p>The LRUCache class in our React app handles the management of tab content. Here, we have used a Doubly linked list data structure. It features two public methods accessible from UI controllers:</p><ol><li>getData(key: string): Returns the content of the tab clicked from the LRU cache. It also marks that content as the most recently used item.</li><li>putData(key: string, value: string): Inserts a new tab content into the LRU cache and marks it as the most recently used item.</li></ol><h3>Application Workflow</h3><ol><li><strong>Tab Click Event:</strong> When a user clicks on a tab, the corresponding content is retrieved using the getData method from the LRUCache. If the content is not available in the cache, it will be fetched from the server (mock server in our case) and the cache will be updated.</li><li><strong>LRUCache Operations:</strong> The LRUCache keeps track of the order of access, ensuring that recently clicked tabs become the most recently used items.</li><li><strong>Capacity Management:</strong> With a set capacity of storing 4 datas, the LRUCache handles eviction by removing the least recently used item when the limit is reached.</li></ol><p>If you’d like to explore the code for the application discussed here, you can clone the following repository.</p><p><a href="https://github.com/souvik-pl/LRU_Cache_react">GitHub - souvik-pl/LRU_Cache_react</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46c48e07e45" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-lru-cache-b46c48e07e45">Understanding LRU Cache</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Browser History Functionality]]></title>
            <link>https://javascript.plainenglish.io/exploring-browser-history-functionality-0488f688e9d2?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/0488f688e9d2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browser-history]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 17:50:36 GMT</pubDate>
            <atom:updated>2024-01-11T01:13:17.910Z</atom:updated>
            <content:encoded><![CDATA[<p>In the vast landscape of web development, understanding the intricacies of browser history functionality is crucial for creating seamless and user-friendly applications. This article delves into a simple yet illustrative web application developed using vanilla HTML, CSS, and JavaScript, designed to showcase the essence of browser history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V8ZKY-3Lh9IRVsLV" /><figcaption>Photo by <a href="https://unsplash.com/@mediamodifier?utm_source=medium&amp;utm_medium=referral">Mediamodifier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>The Browser History App is a straightforward implementation that includes components mimicking a browser’s tab, such as an address bar, home button, backward and forward buttons. The goal is to demonstrate the fundamental aspects of browser history by allowing users to input URLs, navigating backward and forward, and observing the content change accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdGQkfv1Sy_BhsCQTvEF-A.png" /></figure><h3>App Components</h3><h4>1. PageControllerComponent</h4><p>This component houses essential UI elements, including the address bar, home button, and navigation buttons. Users interact with these elements to simulate real-world browser actions.</p><h4>2. PageComponent</h4><p>This component represents the display area for the content corresponding to a URL. Instead of opening the web page corresponding to the URL, we’ll just display Hello from {URL} on the screen.</p><h3>BrowserHistoryService Class</h3><p>The core functionality of the browser history is encapsulated in the BrowserHistoryService class. This class employs two stack data structures to manage the backward and forward navigation, offering methods such as visit(url), back(), and forward().</p><pre>export default class BrowserHistoryService {<br>    constructor() {<br>        this.forwardStack = [];<br>        this.backwardStack = [];<br>    }<br><br>    visit(url) {<br>        this.backwardStack.push(url);<br>        this.forwardStack = [];<br>    }<br><br>    back() {<br>        if (this.backwardStack.length &gt; 1) {<br>            let data = this.backwardStack.pop();<br>            this.forwardStack.push(data);<br>        }<br><br>        return this.backwardStack[this.backwardStack.length - 1];<br>    }<br><br>    forward() {<br>        if (this.forwardStack.length &gt; 0) {<br>            let data = this.forwardStack.pop();<br>            this.backwardStack.push(data);<br>        }<br><br>        return this.backwardStack[this.backwardStack.length - 1];<br>    }<br>}</pre><h3>MessageChannelService Class</h3><p>To enable seamless communication between the PageControllerComponent and PageComponent, the MessageChannelService class is employed. This facilitates the transmission of messages and ensures efficient coordination between different parts of the app.</p><h3>Conclusion</h3><p>This Browser History App serves as a valuable tool for both beginners and experienced developers seeking to grasp the foundations of browser history functionality. By dissecting the code and experimenting with the app, developers can gain insights into the inner workings of browser history and apply this knowledge to enhance their web development skills.</p><p>If you’d like to explore the code for the application discussed here, you can clone the following repository.</p><p><a href="https://github.com/souvik-pl/Browser_History_Design_js">GitHub - souvik-pl/Browser_History_Design_js</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0488f688e9d2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/exploring-browser-history-functionality-0488f688e9d2">Exploring Browser History Functionality</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Non-Critical CSS for Instant Page Load]]></title>
            <link>https://javascript.plainenglish.io/optimizing-non-critical-css-for-instant-page-load-17b83d29a9aa?source=rss-874757c45e99------2</link>
            <guid isPermaLink="false">https://medium.com/p/17b83d29a9aa</guid>
            <category><![CDATA[css-optimization]]></category>
            <category><![CDATA[critical-rendering-path]]></category>
            <category><![CDATA[first-contentful-paint]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Souvik Paul]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 16:48:30 GMT</pubDate>
            <atom:updated>2024-01-02T07:35:10.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VZJ3XiyowOZOqrvK" /><figcaption>Photo by <a href="https://unsplash.com/@laurentmedia?utm_source=medium&amp;utm_medium=referral">toine G</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wondered why some websites take a bit too long to show you anything? There could be multiple reasons, but one of them could be inefficiently loading the CSS files.</p><p>While developing a web page, we write a lot of CSS code. Some of it is necessary for the initial page load (referred to as critical CSS), such as stylings for the application’s skeleton and layout, and stylings for the first page. However, the stylings for other parts of the application, like the contents below the fold of the browser, are not required at the time of the initial load. These stylings can be loaded later after the initial rendering. So, these styles are called non-critical CSS.</p><p>In this article, you will learn to load non-critical CSS files effectively, ensuring they do not block the initial rendering of the page. This optimization enhances the <strong>Critical Rendering Path</strong> and improves the <strong>First Contentful Paint (FCP)</strong>.</p><p>Let’s understand how the browser renders a web page.</p><ol><li>The browser downloads the HTML file and parses it to create the DOM (Document Object Model).</li><li>While parsing the HTML, it encounters a &lt;link&gt; tag referencing an external stylesheet. It downloads that stylesheet and parses it to construct the CSSOM (CSS Object Model).</li><li>Once the DOM and CSSOM have been created, the browser creates a Render Tree by combining the two.</li><li>The next step is called Layouting/Reflow, where the exact size and position are calculated. The output of this step is a “Box Model,” where all the relative measurements are converted to absolute pixels on the screen.</li><li>The final step is to paint the pixels on the screen. This step is called Painting/Rasterizing.</li></ol><p>The above steps that the browser goes through to convert the HTML, CSS, and JavaScript into pixels on the screen are called the Critical Rendering Path. If we can optimize the amount of time spent by the browser on these steps, then we can load the page faster.</p><p>Since CSS files are <strong>render-blocking resources</strong>. They need to be loaded and processed before the browser can show the page. So, it is our responsibility to write less CSS code for the initial page loading purpose.</p><p>Now, let’s take a look at an example. Suppose we want to develop a Vanilla JS application that looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Kkl3ajB9xf6uPHKBBQmKIA.png" /></figure><p>We’ll discuss three approaches to writing the CSS for this application. The third approach will be the optimized one.</p><h4>Approach 1</h4><p>In this approach, our application folder will have only two files — “index.html” and “styles.css”.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Critical CSS loading&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;critical&quot;&gt;<br>        Critical Section<br>    &lt;/div&gt;<br>    &lt;div class=&quot;non_critical&quot;&gt;<br>        Non-Critical Section<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>.critical {<br>    height: 200px;<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    font-size: 30px;<br>    font-weight: 600;<br>    background-color: pink;<br>}<br><br>.non_critical {<br>    height: 200px;<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    font-size: 30px;<br>    font-weight: 600;<br>    background-color: yellow;<br>}</pre><p>Here, both files will be downloaded with the <strong>Highest Priority</strong> and will follow the critical rendering path to be rendered on the screen. The bigger the file, the more time it will take to render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*r-vaefvCHdnnwRtTfLgePw.png" /></figure><h4>Approach 2</h4><p>Here, we will write the non-critical CSS in a separate file. Now, we’ll have three files in the application folder.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Critical CSS loading&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;critical.css&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;non_critical.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;critical&quot;&gt;<br>        Critical Section<br>    &lt;/div&gt;<br>    &lt;div class=&quot;non_critical&quot;&gt;<br>        Non-Critical Section<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>.critical {<br>    height: 200px;<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    font-size: 30px;<br>    font-weight: 600;<br>    background-color: pink;<br>}</pre><pre>.non_critical {<br>    height: 200px;<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    font-size: 30px;<br>    font-weight: 600;<br>    background-color: yellow;<br>}</pre><p>Here also, all three files will be downloaded with the <strong>Highest Priority</strong> and will follow the critical rendering path to be rendered on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*aTUQAyedh7Jbe3KKu0oWnA.png" /></figure><h4>Approach 3</h4><p>In this approach, we’ll make a few changes in the way we are loading the non-critical CSS file. The code of both the CSS files will remain the same as in the previous approach. Only the “index.html” will be updated.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Critical CSS loading&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;critical.css&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;non_critical.css&quot; media=&quot;print&quot; onload=&quot;this.media=&#39;all&#39;&quot;&gt;<br>    &lt;noscript&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;non_critical.css&quot;&gt;&lt;/noscript&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;critical&quot;&gt;<br>        Critical Section<br>    &lt;/div&gt;<br>    &lt;div class=&quot;non_critical&quot;&gt;<br>        Non-Critical Section<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In the above code, the following line is doing all the magic.</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;non_critical.css&quot; media=&quot;print&quot; onload=&quot;this.media=&#39;all&#39;&quot;&gt;</pre><p>When the browser parses the HTML, it will see the &lt;link&gt; tag has media=&quot;print&quot;, and it will download this file asynchronously with the <strong>Lowest Priority</strong>, without blocking the rendering. Hence, it will not be part of the initial rendering process. After the initial rendering, the &quot;non_critical.css&quot; will be parsed and applied to the page.</p><p>Since we are also attaching an onload handler function this.media=&#39;all&#39; in the above &lt;link&gt; tag, which will only work if the user&#39;s browser has JavaScript enabled. To make it work even if JavaScript is disabled, we need to add the following.</p><pre>&lt;noscript&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;non_critical.css&quot;&gt;&lt;/noscript&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*Rm_s9yR6w9Oq-ePMA-8BbQ.png" /></figure><p>Now, let’s see how this approach affects the UI. If we throttle down the network speed in developer tools, we’ll be able to see that once the initial rendering is done, the UI will look like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*h_fCSt-8swvwoVjlM3ulRQ.png" /></figure><p>After the styles from “non_critical.css” get applied, the UI will look like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*iMNZChxXb9Va-NM27d5edQ.png" /></figure><p>In conclusion, optimizing the loading of non-critical CSS files emerges as a crucial strategy for enhancing web page performance. By strategically managing the rendering path and prioritizing critical styles for initial display, we can significantly reduce the time it takes for users to see the content.<br> If you’d like to explore the code for the application discussed here, you can clone the following repository.</p><p><a href="https://github.com/souvik-pl/Non_Critical_CSS_Optimization">GitHub - souvik-pl/Non_Critical_CSS_Optimization</a></p><h3><a href="https://plainenglish.io/">PlainEnglish.io</a> 🚀</h3><p><em>Thank you for being a part of the In Plain English community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer</em><strong>️</strong></li><li><em>Learn how you can also </em><a href="https://plainenglish.io/blog/how-to-write-for-in-plain-english"><strong><em>write for In Plain English</em></strong></a><em>️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>X</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em> | </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em> | </em></strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em> | </em></strong><a href="https://newsletter.plainenglish.io/"><strong><em>Newsletter</em></strong></a></li><li><em>Visit our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><strong><em> | </em></strong><a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a><strong><em> | </em></strong><a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17b83d29a9aa" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/optimizing-non-critical-css-for-instant-page-load-17b83d29a9aa">Optimizing Non-Critical CSS for Instant Page Load</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>