<?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 BharatPe on Medium]]></title>
        <description><![CDATA[Stories by BharatPe on Medium]]></description>
        <link>https://medium.com/@bharatpe?source=rss-3ab5c74e0bc9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cV6T5YsTHzawErkLMVBoeQ.jpeg</url>
            <title>Stories by BharatPe on Medium</title>
            <link>https://medium.com/@bharatpe?source=rss-3ab5c74e0bc9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:53:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bharatpe/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[Unfolding The Service Worker]]></title>
            <link>https://engineering.bharatpe.com/unfolding-the-service-worker-52425c3e2c8e?source=rss-3ab5c74e0bc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/52425c3e2c8e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[BharatPe]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 09:56:52 GMT</pubDate>
            <atom:updated>2024-02-13T09:56:52.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pGDei5sKPfLBi-GQw268g.jpeg" /></figure><p>Hey Developers, I am sure most of you are already aware of Service Workers and their applications. While those who don’t know just think of it like a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction like caching etc. So, In our applications at BharatPe, we were trying to implement caching to optimize the performance of our applications and while doing so we faced blockers in cache management.</p><p>Let’s learn how these service workers work by default and at which stage we faced this issue and then how we tackled this issue in our BharatPe applications.</p><p>How Service Workers works w.r.t Caching</p><p>With the help of service workers, we implement caching and cache the static files in the browser. When you cache your static files, your application becomes faster and is helpful for even running your application offline. Let’s understand this using below data flow diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-QWPwOPR_6ECdCvs6Gdlw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjlhdZg5et6EJnrIZJglkQ.jpeg" /></figure><p>Now, when the user goes to a website/application, then they receive the information from the cached stored data file and in the background, the service worker will connect with the server and check whether there is any update that is pushed into the server. Now if there is no update, then there is everything great. But if there is an update then the service worker fetch the updated data files and store them (they are not served yet, they are in the waiting phase). Have a look at the below diagram showing data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gYI6h8h-vEyP9gVc46NxA.jpeg" /></figure><p>Now the updated files are in a waiting state until it’s required to get swapped with the older one. Now you might be thinking when should that swap happen? When the user refreshes the page or anything else? This is what the problem is, the default behaviour of the service workers is that when the page refreshes, it fetches the data from cached files only and our newly updated content is in waiting for state only. Have a look at the below diagram showing data flow once the user refreshes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hKBjcKw4_0JdLNLXx_3AA.jpeg" /></figure><p>Now this could be accomplished by closing the tab of the application (if it’s a web application) and then opening it again. There are other conditions also that these service workers see other than the closing tab. These service workers also have a function called skipWaiting(), which skips the waiting time of the updated data and renders the updated data once the user refreshes the page i.e user is delayed by just n+1 state. This concept sounds amazing theoretically, but as I already mention, there are several other parameters also that these service workers see, and the result is that even after multiple refreshed and new tab sessions, the latest updates were not rendering. The in-build service worker of React JS was also discarded due to this reason only and they stop providing inbuilt service workers support.</p><p>In the case of BharatPe applications, the problem is same, as we use web view to render our applications into mobile screens, hence we are not able to close the tab, and then the refresh thing is not working practically in either of the cases. This thing is possible only when you clear caches and browser history, but we can’t expect all users are technically sound.</p><p>Solution 1 is that we monitor the latest files or versions via our code and whenever there is any new version available i.e the current version and the last updated versions are mismatched then we can give a popup to the user that a new update is available. You might have seen such kinds of pop-up messages in a few applications like Gmail etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*OmdC4GLCoj8044EdnMORTA.jpeg" /></figure><p>But this is not a good solution with respect to the UX point of view, this looks less prominent way to deal with this problem. Because every time the user comes to our application and we release something new, this pop-up occurs and the user has to do it again and again. It’s so awkward :(</p><p>⚠ Warning ⚠ — There are possibilities that you might deliver a bad or malfunctioned service workers, which is really a very bad impression to your users. Because delivering bad service worker is something which you can’t resolve even after releasing any new update. It will be a huge problem with a very bad impact. The only way to revert back is to release a new deployment with either a good service worker or remove that and then ask your users to clear the cache of browsers and cookies and then use your application. Which is so bad w.r.t the user’s point of view.</p><p>We have created our own service worker and we are resolving this issue by EVH (External version handler). The main steps of our service worker include SW Registration, SW Installation, and SW Activation.</p><blockquote>Main Idea is to get the version from version.json of the new build. And compare it with the existing version inside the cache. if they are the same then do nothing else clear the old cache, unregister the service worker and re-register it.</blockquote><p>Note — I will be demonstrating for the React JS + Typescript project. You can change it as per your stack.</p><p><strong>Step 1</strong></p><p>Configure your service worker which will be used to generate the final service worker script with all the details of the assets that are to be cached.</p><ul><li>Service Worker Config, name the file as “src/service-worker.ts” (We are using workbox for config)</li></ul><pre>import { clientsClaim } from &#39;workbox-core&#39;;<br>import { ExpirationPlugin } from &#39;workbox-expiration&#39;;<br>import { precacheAndRoute, createHandlerBoundToURL } from &#39;workbox-precaching&#39;;<br>import { registerRoute } from &#39;workbox-routing&#39;;<br>import { StaleWhileRevalidate } from &#39;workbox-strategies&#39;;<br><br>clientsClaim();<br><br>// PreCaching all the urls from manifest file.<br>precacheAndRoute(self.__WB_MANIFEST);<br><br>// Forming a App Shell;<br>const fileExtensionRegexp = new RegExp(&#39;/[^/?]+\\.[^/]+$&#39;);<br>registerRoute(<br>    ({ request, url }) =&gt; {<br>        // If this isn&#39;t a navigation, skip.<br>        if (request.mode !== &#39;navigate&#39;) {<br>            return false;<br>        }<br><br>        if (url.pathname.startsWith(&#39;/_&#39;)) {<br>            return false;<br>        }<br><br>        if (url.pathname.match(fileExtensionRegexp)) {<br>            return false;<br>        }<br><br>        return true;<br>    },<br>    createHandlerBoundToURL(process.env.PUBLIC_URL + &#39;/index.html&#39;)<br>);<br><br>// Runtime assets<br>registerRoute(<br>    ({ url }) =&gt; url.origin === self.location.origin &amp;&amp; (url.pathname.endsWith(&#39;.png&#39;) || url.pathname.endsWith(&#39;.jpg&#39;) || url.pathname.endsWith(&#39;.sv&#39;)), // Customize this strategy as needed, e.g., by changing to CacheFirst.<br>    new StaleWhileRevalidate({<br>        cacheName: &#39;images&#39;,<br>        plugins: [<br>            new ExpirationPlugin({ maxEntries: 5 }),<br>        ],<br>    })<br>);<br><br>// Trigger skipwaiting<br>self.addEventListener(&#39;message&#39;, (event) =&gt; {<br>    if (event.data &amp;&amp; event.data.type === &#39;SKIP_WAITING&#39;) {<br>        self.skipWaiting();<br>    }<br>});</pre><p><strong>Step 2</strong></p><p>Now we need to have a script that generates version on every build release. Which is a external version file (version.json)</p><ol><li>Create a new folder named “script” and add the below script inside this folder with the name “pre-release.js”</li></ol><pre>const path = require(&#39;path&#39;);<br>const fs = require(&#39;fs-extra&#39;);<br><br>const PACKAGE_PATH = process.cwd();<br>const BUILD_PATH = path.join(PACKAGE_PATH, &#39;./public&#39;);<br><br>/**<br> * @name getVersion<br> * @returns {string} version<br> */<br>const getVersion = async() =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const packageFile = path.join(PACKAGE_PATH, &#39;package.json&#39;);<br>        console.log(&#39;reading package&#39;);<br>        fs.readFile(packageFile, (err, data) =&gt; {<br>            if (err)<br>                resolve(null)<br>            const packageJson = JSON.parse(data);<br>            resolve(packageJson.version);<br>        })<br>    });<br>}<br><br>/**<br> * Generate version.json file for build folder<br> * @param {*} buildPath <br> * @returns <br> */<br>async function createVersionFile(buildPath) {<br>    const version = await getVersion();<br>    if (!version) return;<br><br>    const versionContent = {<br>        version<br>    };<br>    console.log(versionContent, &quot;JSON&quot;);<br>    const versionJsonPath = path.join(BUILD_PATH, &#39;version.json&#39;);<br><br>    await Promise.all([<br>        fs.writeFile(versionJsonPath, JSON.stringify(versionContent, null, 2)),<br>    ]);<br>}<br><br>// Generate version.json<br>createVersionFile(BUILD_PATH);</pre><p>2. Update the build script in your package.json as</p><pre> &quot;build&quot;: &quot;node scripts/pre-release.js &amp;&amp; react-scripts build&quot;</pre><p>This will generate the version as planned and then the build will generate.</p><p><strong>Step 3</strong></p><p>Service worker handler, This is to register, unregister, version checker, handling cache etc. This is like a service which manages the service worker flow</p><pre>function registerValidSW(swUrl: string, config: any) {<br>    navigator.serviceWorker<br>        .register(swUrl)<br>        .then((registration) =&gt; {<br>            registration.onupdatefound = () =&gt; {<br>                const installingWorker = registration.installing;<br>                if (installingWorker == null) {<br>                    return;<br>                }<br>                installingWorker.onstatechange = () =&gt; {<br>                    if (installingWorker.state === &#39;installed&#39;) {<br>                        if (navigator.serviceWorker.controller) {<br>                            console.log(&#39;New content is fetched but yet to service!!&#39;);<br>                        } else {<br>                            console.log(&#39;Content is precached now !!&#39;);<br>                        }<br>                    }<br>                };<br>            };<br>        })<br>        .catch((error) =&gt; {<br>            console.error(&#39;Error during service worker registration:&#39;, error);<br>        });<br>}<br><br>function checkValidServiceWorker(swUrl: string, config: any) {<br>    fetch(swUrl, {<br>        headers: { &#39;Service-Worker&#39;: &#39;script&#39; },<br>    })<br>        .then((response) =&gt; {<br>            const contentType = response.headers.get(&#39;content-type&#39;);<br>            if (response.status === 404 || (contentType != null &amp;&amp; contentType.indexOf(&#39;javascript&#39;) === -1)) {<br>                navigator.serviceWorker.ready.then((registration) =&gt; {<br>                    registration.unregister().then(() =&gt; {<br>                        window.location.reload();<br>                    });<br>                });<br>            } else {<br>                registerValidSW(swUrl, config);<br>            }<br>        })<br>        .catch(() =&gt; {<br>            console.log(&#39;No internet connection found. App is running in offline mode.&#39;);<br>        });<br>}<br><br>const isLocal = Boolean(<br>    window.location.hostname === &#39;localhost&#39; ||<br>        window.location.hostname === &#39;[::1]&#39; ||<br>        window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/),<br>);<br><br>export function register(currentBuildVersion: any) {<br>    if (process.env.NODE_ENV === &#39;production&#39; &amp;&amp; &#39;serviceWorker&#39; in navigator) {<br>        const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);<br>        if (publicUrl.origin !== window.location.origin) {<br>            return;<br>        }<br><br>        window.addEventListener(&#39;load&#39;, async () =&gt; {<br>            // Clearing old data if any<br>            const versionJSON = `${process.env.PUBLIC_URL}/version.json`;<br>            const JSONResponse = await fetch(versionJSON);<br>            const versionData = await JSONResponse.json();<br>            const buildVersion = versionData.version;<br>            const cacheStatus = await clearCacheOnNewBuild(currentBuildVersion, buildVersion);<br>            if (cacheStatus == &#39;deleted&#39;) {<br>                await unregister();<br>                document.location.reload();<br>            }<br><br>            console.log(&#39;resolved&#39;, cacheStatus);<br><br>            // Registration<br>            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;<br><br>            if (isLocal) {<br>                checkValidServiceWorker(swUrl, null);<br>                navigator.serviceWorker.ready.then(() =&gt; {<br>                    console.log(&#39;Service Worker Activated&#39;);<br>                });<br>            } else {<br>                // Is not localhost. Just register service worker<br>                registerValidSW(swUrl, null);<br>            }<br>        });<br>    }<br>}<br><br>export function unregister() {<br>    return navigator?.serviceWorker?.ready<br>        .then((registration) =&gt; {<br>            return registration.unregister();<br>        })<br>        .catch((error) =&gt; {<br>            return console.error(error.message);<br>        });<br>}<br><br>export const clearCacheOnNewBuild = (currentBuildVersion: string, buildVersion: string) =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;New BuildVersion&#39;, buildVersion, &#39;Current BuildVersion&#39;, currentBuildVersion);<br>        if (currentBuildVersion !== buildVersion) {<br>            // eslint-disable-next-line no-console<br>            console.log(&#39;New version found.&#39;);<br>            if (buildVersion) {<br>                if (&#39;caches&#39; in window) {<br>                    caches.keys().then((keyList) =&gt; {<br>                        return Promise.all(<br>                            keyList.map((key) =&gt; {<br>                                return caches.delete(key);<br>                            }),<br>                        );<br>                    });<br>                    resolve(&#39;deleted&#39;);<br>                }<br>            }<br>        }<br>        resolve(&#39;loading&#39;);<br>    });<br>};</pre><p><strong>Step 4</strong></p><p>Initialise the service worker in your application. Add the below code into your index file along with your existing code.</p><pre>import * as ServiceWorker from &#39;./ServiceWorkerCore&#39;;<br>const pjson = require(&#39;../package.json&#39;);<br><br>try {<br>    // Register worker<br>    ServiceWorker.register(pjson.version);<br>} catch (e) {<br>    console.error(&#39;Service Worker Failed&#39;, e);<br>}</pre><p>With these 4 steps, We can have a perfect service worker which effiencetly handles cache &amp; improves overall performance.</p><p>This is for CRA based react projects. For web pack based projects the workbox part slightly changes a bit. We don’t need the service-worker.ts file, Instead add these in you webpack config.</p><p>Generating service worker</p><pre>new WorkboxPlugin.GenerateSW({<br>    clientsClaim: true,<br>    skipWaiting: true,<br>    exclude: [&#39;version.json&#39;]<br>}),</pre><p>Copying the version file from public to build folder</p><pre>new CopyWebpackPlugin({<br>    patterns: [{<br>        from: path.resolve(__dirname + &#39;/public&#39;, &quot;version.json&quot;),<br>    }]<br>}),</pre><p>This should work the same way as CRA.</p><p>This is how we were able to achieve this great performance with our own custom worker. I hope after reading this the fear inside you of the service workers vanishes and you were able to increase the performance of your application. In case of any doubts feel free to drop us your doubts at <a href="/service/mailto:tech.queries@bharatpe.com">tech.queries@bharatpe.com</a> or you can comment below and our team will try to respond to you as soon as possible.</p><p>Do follow us on <a href="https://twitter.com/bharatpeindia">Twitter</a>, <a href="https://www.linkedin.com/company/bharatpe/about/">LinkedIn</a>, we post our geeky stuff very frequently here. Also, if you are looking to join our geeky engineering team, do check out <a href="https://tech.bharatpe.com/">tech.bharatpe.com</a> we have a lot of openings for the candidates who believe in building a new generation of revolutionary fintech products and building a new INDIA together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52425c3e2c8e" width="1" height="1" alt=""><hr><p><a href="https://engineering.bharatpe.com/unfolding-the-service-worker-52425c3e2c8e">Unfolding The Service Worker</a> was originally published in <a href="https://engineering.bharatpe.com/">BharatPe Tech Chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AssetGuard: Keeping Assets in Check via Husky or Github Action]]></title>
            <link>https://engineering.bharatpe.com/assetguard-keeping-assets-in-check-via-husky-or-github-action-890b75808128?source=rss-3ab5c74e0bc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/890b75808128</guid>
            <category><![CDATA[husky]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[BharatPe]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 07:35:48 GMT</pubDate>
            <atom:updated>2024-01-11T07:35:48.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StdlYaaJSrF1Zuk3PNHlPw.jpeg" /></figure><p>In the startup hassle, product development is always the highest priority, and due to this race to build and ship products in a very short period, we generally forget to follow some basic coding practices. One of the problems among them is the use of the optimal size of the images.</p><p><strong>Problem Statement — </strong>To automate the blocking of the use of assets that are higher than a threshold value (eg. 100kb).</p><p><strong>The Approach —</strong> To solve this problem using some automation we identified 2 break points where some automation can be added i.e. at the developer’s end and the PR reviewer’s end. The idea is to first warn the developer before pushing it into our VCS that your changes contain some assets that are greater than 100kb and secondly, to provide some information about the assets in Pull Request so that the reviewer will get to know. This will help us to determine if the developer ignored and pushed directly into VCS.</p><p><strong>Breakpoint 1:</strong> To make sure the developer will get the warning while pushing his changes into GitHub, I created a script that will run as a pre-commit. To implement this, I used a husky and a bash script.<br>In the bash script, I first checked the count of all the assets that are greater than 100kb and stored it. Now, if the count is greater than zero, I will post a warning instruction in the terminal and if the count is 0, then I will print out a congratulations message in the terminal.</p><pre>NC=&#39;\033[0m&#39;<br>YELLOW=&#39;\033[0;33m&#39;<br>GREEN=&#39;\033[0;32m&#39;<br>count=$(find ./src/assets/ -type f -size +100k -exec ls -lh {} \; | wc -l)<br>if [[ &quot;${count}&quot; -gt 0 ]]; then <br>    find ./src/assets/ -type f -size +100k -exec ls -lh {} \; | awk &#39;{ print &quot;\033[31m&quot; $9 &quot; || Size : &quot; $5 }&#39;<br>    printf &quot;${YELLOW}INFO: Please resize above assets and then proceed${NC}\n\n&quot;<br>else<br>    printf &quot;${GREEN}Congratulations, all images are less than 100Kb.${NC}\n\n&quot;;<br>fi<br># Script Ends</pre><p>In the package.json, add husky logic and script command.</p><pre>&quot;husky&quot;: {<br>  &quot;hooks&quot;: {<br>      &quot;pre-commit&quot;: &quot;yarn run asset-test&quot;<br>  }<br>}</pre><p>Add script in dependencies. (Note — You can replace the “scripts/<a href="http://pre-asset-check.sh/">pre-asset-check.sh</a>” path to your file where it’s located in your code).</p><pre>&quot;asset-test&quot;: &quot;chmod +x scripts/pre-asset-check.sh &amp;&amp; bash scripts/pre-asset-check.sh&quot;</pre><p><strong>Breakpoint 2:</strong> Now when the developer has raised the pull request, I created a new GitHub action which will automatically triggered when any new PR is raised or new changes in PR are pushed.<br>To create a new GitHub action, I followed an amazing article by FreeCodeCamp <a href="https://www.freecodecamp.org/news/build-your-first-javascript-github-action/">https://www.freecodecamp.org/news/build-your-first-javascript-github-action/</a> and created my files as per requirement.</p><p>Action metadata file — This will help us to define the interface of our Action.</p><pre>name: &#39;Assets Checker&#39;<br>description: &#39;A Github Action to Analyse your static image files and warns if the size increase the threshold size. It check for .jpg, .svg, .png, .gif, .jpeg files.&#39;<br>author: &#39;BharatPe&#39;<br>inputs:<br>  target_folder:<br>    description: &#39;The path of directory which contains all your assets ex. src/assets&#39;<br>    required: true<br>    default: src/assets<br>  thrashold_size:<br>    description: &#39;Maximum size of assets allowed in Kb ex. 100&#39;<br>    required: true<br>    default: 100<br>  token:<br>    description: &#39;The token to use to access the GitHub API&#39;<br>    required: true<br>runs:<br>  using: &#39;node16&#39;<br>  main: &#39;dist/index.js&#39;</pre><p>Now, using handy toolkits from GitHub i.e. actions@core, and actions@gituhub, we will make the heart of our action i.e. action file.</p><pre>const core = require(&quot;@actions/core&quot;);<br>const github = require(&quot;@actions/github&quot;);<br>const exec = require(&quot;@actions/exec&quot;);<br>const { Octokit } = require(&quot;@octokit/rest&quot;);<br>const fs = require(&#39;fs&#39;);<br><br>const convertBytes = function(bytes) {<br>  const sizes = [&quot;Bytes&quot;, &quot;KB&quot;, &quot;MB&quot;, &quot;GB&quot;, &quot;TB&quot;]<br><br>  if (bytes == 0) {<br>    return &quot;n/a&quot;<br>  }<br><br>  const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))<br><br>  if (i == 0) {<br>    return bytes + &quot; &quot; + sizes[i]<br>  }<br><br>  return (bytes / Math.pow(1024, i)).toFixed(1) + &quot; &quot; + sizes[i]<br>}<br><br>const main = async () =&gt; {<br>  try {<br><br>    const inputs = {<br>      token: core.getInput(&quot;token&quot;),<br>      target_folder: core.getInput(&quot;target_folder&quot;),<br>      thrashold_size: core.getInput(&quot;thrashold_size&quot;)<br>    };<br><br>    const {<br>      payload: { pull_request: pullRequest, repository },<br>    } = github.context;<br><br>    if (!pullRequest) {<br>      core.error(&quot;This action only works on pull_request events&quot;);<br>      return;<br>    }<br><br>    const { number: issueNumber } = pullRequest;<br>    const { full_name: repoFullName } = repository;<br>    const [owner, repo] = repoFullName.split(&quot;/&quot;);<br><br>    const octokit = new Octokit({<br>      auth: inputs.token,<br>    });<br><br>    let ignoreArray = [];<br>    let myOutput = &#39;&#39;;<br>    let myError = &#39;&#39;;<br>    const options = {};<br><br>    options.listeners = {<br>      stdout: (data) =&gt; {<br>        myOutput += data.toString();<br>      },<br>      stderr: (data) =&gt; {<br>        myError += data.toString();<br>      }<br>    };<br><br>    /**<br>     * Check if array assets file name contains inside .ignore-assets file or not.<br>     * If its contains then remove those images from sourceArray and return new array.<br>     * <br>     * @param {Array} sourceArray Array of all assets files.<br>     * @returns Array of files.<br>     */<br>    function getAssetsIgnoreFiles(sourceArray) {<br>      const file=`.assets-ignore`;<br>      try {<br>        ignoreArray = fs.readFileSync(file).toString().split(&quot;\n&quot;);<br><br>        if (ignoreArray.length &gt; 0) {<br>          return sourceArray.filter (v =&gt; {<br>            const fileName = v.split(&quot; &quot;).slice(-1).pop()<br>            if (!fileName) return true;<br>            return ignoreArray.indexOf(fileName) === -1;<br>          })<br>        }<br>      } catch (e) {<br>        // File not found exception.<br>      }<br><br>      return sourceArray;<br>    }<br><br>    await exec.exec(`find ${inputs.target_folder} -type f \( -name &quot;*.jpeg&quot; -o -name &quot;*.png&quot; -o -name &quot;*.svg&quot; -o -name &quot;*.gif&quot; -o -name &quot;*.jpg&quot; \) -size +${inputs.thrashold_size}k -exec ls -lh {} \;`, null, options);<br><br>    const arrayOutput = getAssetsIgnoreFiles(myOutput.split(&quot;\n&quot;));<br><br>    const count = arrayOutput.length - 1;<br><br>    const invalidFiles = [...arrayOutput];<br><br>    const successBody = ` Woohooo :rocket: !!! Congratulations, your all assets are less than ${inputs.thrashold_size}Kb.`<br>    const errorBody = `Oops :eyes: !!! You have ${count} assets with size more than ${inputs.thrashold_size}Kb. Please optimize them. If you unable to optimize these assets, you can use .assets-ignore file and add these assets in .assets-ignore file. For more details read readme`<br><br>    const getTableDataString = (invalidFiles) =&gt; {<br>      let filteredFiles = [];<br><br>      for(let item of invalidFiles) {<br>        const fileName = item.split(&quot; &quot;).slice(-1).pop();<br>        const fileSize = item.split(&quot; &quot;)[4];<br>        if(fileName &amp;&amp; fileSize) filteredFiles.push([fileName, fileSize]);<br>      }<br><br>      let res = `### Invalid Files\n|File Name|File Size|\n|-----|:-----:|\n`;<br>      for(let item of filteredFiles) {<br>        res += `|${item[0]}|${item[1]}|\n`<br>      }<br>      return res;<br>    };<br><br>    /**<br>     * Get all Ignored file data as github comment string format.<br>     * <br>     * @param {Array} ignoreArray array of files which is added in .assets-ignore file.<br>     * @returns Promise of github comment string.<br>     */<br>    const getAllIgnoredFileString = (ignoreArray) =&gt; {<br>      return new Promise((resolve, reject) =&gt; {<br>        let res = `### All .assets-ignored Files\n|File Name|File Size\n|-----|:-----:|\n`;<br>        for(let index=0; index &lt; ignoreArray.length; index++) {<br>          const item = ignoreArray[index];<br><br>          fs.stat(item, (err, fileStats) =&gt; {<br>            if (err) {<br>              res += `|${item}|None|\n`<br>            } else {<br>              const result = convertBytes(fileStats.size)<br>              res += `|${item}|${result}|\n`<br>            }<br><br>            if (index === ignoreArray.length-1) {<br>              resolve(res);<br>            }<br>          })<br>        }<br>      })<br>    };<br><br>    /**<br>     * Publish .assets-ignore entries in github comment.<br>     * <br>     * @param {Array} ignoreArray array of files which is added in .assets-ignore file.<br>     */<br>    const publishIgnoreAssetsTable = async (ignoreArray) =&gt; {<br>      if (ignoreArray.length) {<br>        const body = await getAllIgnoredFileString(ignoreArray);<br>        return octokit.rest.issues.createComment({<br>          owner,<br>          repo,<br>          issue_number: issueNumber,<br>          body,<br>        });<br>      }<br>    }<br><br>    if(count &gt; 0) {<br>      octokit.rest.issues.createComment({<br>        owner,<br>        repo,<br>        issue_number: issueNumber,<br>        body: errorBody,<br>      });<br><br>      octokit.rest.issues.createComment({<br>        owner,<br>        repo,<br>        issue_number: issueNumber,<br>        body: getTableDataString(invalidFiles),<br>      });<br><br>      await publishIgnoreAssetsTable(ignoreArray);<br><br>      core.setFailed(&#39;Invalid size assets exists !!!&#39;);<br>    }else {<br>      octokit.rest.issues.createComment({<br>        owner,<br>        repo,<br>        issue_number: issueNumber,<br>        body: successBody,<br>      });<br><br>      await publishIgnoreAssetsTable(ignoreArray);<br>    }<br><br>  } catch (error) {<br>    core.setFailed(error.message);<br>  }<br>};<br><br>main();</pre><p>Now, after putting this final logic and building, we get our GitHub action ready to be used across any repository. To test and use our action, you can simply create a workflow file in your application under the .github folder ex. .github/workflows/asset-checker.yml, and add below code into your yml file.</p><pre>name: &#39;Assets Checker by BharatPe&#39;<br><br>on: [pull_request]<br>jobs:<br>  Assets-Checker:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@master<br>      - uses: actions/setup-node@v1<br>        with:<br>          node-version: &#39;14.15.0&#39;<br>      - uses: bharatpe/assets-checker@main<br>        with:<br>          token: ${{ secrets.GITHUB_TOKEN }}<br>          target_folder: src/assets<br>          thrashold_size: 100</pre><p>You can configure it according to your use case by providing input values in <em>target_folder</em>, <em>thrashold_size</em>, etc.</p><p><em>Note </em>— <em>There might be some cases where you have to use files greater in size, and for that, we have provided support with our asset-ignore config.</em> <em>Thanks, Sandeep Rawat for this feature.</em></p><p>For more information, check our repository at <a href="https://github.com/bharatpe/assets-checker">https://github.com/bharatpe/assets-checker</a> and give it a star ⭐ if you like it.</p><p>Hence, my first GitHub action for BharatPe is built and I am super proud that it is being used by almost all frontend repositories across our organization. In case of any doubts feel free to comment below and our team will try to respond to you as soon as possible or connect with me at <a href="https://www.linkedin.com/in/akshaysharma008/">Akshay Sharma</a>.</p><p>Do follow us on <a href="https://twitter.com/bharatpeindia">Twitter</a>, and <a href="https://www.linkedin.com/company/bharatpe/about/">LinkedIn</a>, we post our geeky stuff very frequently here. Also, if you want to join our geeky engineering team, check out the careers page. We have openings for candidates who believe in building a new generation of revolutionary fintech products and building a new INDIA together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890b75808128" width="1" height="1" alt=""><hr><p><a href="https://engineering.bharatpe.com/assetguard-keeping-assets-in-check-via-husky-or-github-action-890b75808128">AssetGuard: Keeping Assets in Check via Husky or Github Action</a> was originally published in <a href="https://engineering.bharatpe.com/">BharatPe Tech Chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your ReactJS App with Optimized Infinite Scrolling]]></title>
            <link>https://engineering.bharatpe.com/supercharge-your-reactjs-app-with-optimized-infinite-scrolling-c11420189ebe?source=rss-3ab5c74e0bc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11420189ebe</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[infinite-scrolling]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[BharatPe]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 13:09:08 GMT</pubDate>
            <atom:updated>2024-01-08T12:39:03.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1zOF1YkQzRNNKjlxh79eQ.jpeg" /></figure><p>Infinite Scrolling with Collapsible Headers: The Virtual Approach</p><h3>UI Scroll:</h3><p>Scrolling is a method used to display data when it is not possible to fit all the content onto a single page. This implementation is commonly seen on most websites, such as Twitter and Facebook feeds or lists of items on an e-commerce app like <a href="https://zillionrewards.in/">Zillion</a>, where the content cannot be accommodated entirely on the computer screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*PBG5uj6LAnzbppH-ci1-iQ.gif" /></figure><h3>The naive way and its consequences:</h3><p>To implement this concept easily, we can initially display all the data on the screen. However, a challenge arises when the number of items becomes substantial. For instance, consider Facebook feeds with a large list of items. Displaying all of them on the screen is not practical due to the potentially huge number, which could reach hundreds, thousands, or even more. Creating many DOM nodes to show the data is not an optimal solution in such cases.</p><h3>Improved Approach:</h3><p>One possible solution for this is implementing Pagination. In this approach, our documents are organized into pages, each containing a specific number of items. Users can navigate forward and back through the pages using either the page number or the arrow icon, similar to flipping through pages in a manual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-7jDUHzsqgHE7b8ioNGLw.jpeg" /></figure><p>From a technical standpoint, this approach is logical, as we organize items by content page in our database, and we serve the correct data based on the user’s input. However, we can explore a more efficient and user-friendly solution. What if we dynamically change the pages for the user as they scroll?</p><p>Infinite Scroll offers a solution to this issue. With this method, we can dynamically append pages as the user scrolls, incrementing the page one at a time until all pages are displayed. By adopting this approach, we can reduce interaction costs, particularly on mobile devices, by eliminating the need for extra clicks from users.</p><h3>Implementation:</h3><p>To enable infinite scroll on our list, we can attach an event listener to the scroll event. This will allow us to detect when we reach the bottom of the page and subsequently trigger the loading of more items for our list. However, doing this can result in both noise and non-performant Javascript code because of the event listeners’ nature. When optimizing the front-end code, our goal should be to minimize the number of listeners whenever feasible.</p><h3>Here comes Intersection Observer to save us:</h3><p>The Intersection Observer is a JavaScript API that allows you to efficiently observe changes in the visibility of an element within the viewport or a specific container. It provides a way to track when an observed element enters or exits the visible part of the user’s browser window.</p><p>The Intersection Observer is especially useful for implementing lazy loading of images, infinite scrolling, and other performance optimizations in web applications. It helps avoid costly computations and improves the performance of websites by reducing the need for continuous manual checks of element visibility.</p><p>The basic idea behind Intersection Observer is that you define a callback function that will be executed whenever an observed element crosses a specified threshold (i.e., enters or exits the viewport). This callback function receives a list of IntersectionObserverEntry objects that contain information about the observed element, such as its visibility percentage, bounding rectangle, and intersection ratio.</p><p>One significant advantage of using this API compared to event listeners is that the computation for both the target elements and observing the behaviour of intersecting elements is not executed on the main JavaScript thread. This means we are freed from the potential noise and blocking nature of the language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*zrBz4RqkGtRptQl0DlAflw.jpeg" /></figure><h3>Mechanism</h3><p>However, before we proceed with the solution, we must consider a few points. While Intersection Observer offers advantages over a regular scroll event listener, it alone will not completely solve the problem. If we simply append the next data to the end of the existing list, we will still create a large number of DOM nodes, which is not an optimal solution.</p><p>We should aim to minimize the count of visible DOM elements while ensuring it is larger than the viewport (our root element). For this purpose, we will set the count to 20 in our specific case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Uqfecx1PBXm5hS7JJwh_Cw.gif" /></figure><blockquote><em>As observed, the total number of DOM elements remains constant, as we navigate through the complete list. To create an illusion of a large scrolling list, we dynamically modify the attributes, contents, and paddings of these elements.</em></blockquote><p>We will become acquainted with several keywords related to constructing an infinite scroll feature, and then I will explore each one in detail.</p><ol><li>Root Element</li><li>Watcher</li><li>Virtual DOM</li><li>Virtual Scrolling</li></ol><p>The Root Element serves as our observation target for the sentinels. Whenever the sentinels intersect with this element, we initiate the computation process to either fetch new items from an API or retrieve them directly from the cache. This term is derived from the Intersection Observer API. By extending the root margin at the bottom, we ensure that the fetch call occurs well before the content reaches the viewport, thereby minimizing the waiting time for the user to receive the new data.</p><p>The Watchers serve as fixed elements that act as triggers for initiating changes. In the case of implementing an infinite scroll, we utilize top and bottom anchors to detect changes whenever they intersect with our Root Element. The top watcher operates straightforwardly, as it returns the data stored in our cache (in memory, Redis map, etc.) and displays it.</p><p>On the other hand, the bottom watcher presents a more intricate scenario. Depending on the sliding window, we must decide whether to make a network request for more data or retrieve it from the existing cache (if the user scrolls up and then back down). For our demonstration purposes, we will simplify this process by assuming that all data already exists in the cache. However, it’s important to remember that in real-world scenarios, we need to include a fetch call when the data from the cache is exhausted.</p><p>The Virtual DOM plays a crucial role in preventing the need to repaint the entire browser when displaying new items. Instead of performing a full re-render, we can update the attributes to show the new data. Additionally, by strategically adjusting the container’s paddings, we can create the illusion of extending the list to the user without actually expanding it in the DOM. In the demo, I will provide a detailed explanation of this implementation.</p><p>Virtual Scrolling is related to the intervals between two indices while scrolling up or down, which includes the number of visible DOM nodes. By employing this sliding window approach, we can restrict the display to a fixed amount of data, leaving the rest of the content outside the current viewport.</p><p>Now that we have covered those points, let’s proceed to the actual demo.</p><h3>Few notable functions:</h3><ol><li>topWatcherElmRef</li><li>bottomWatcherElmRef</li><li>topReachedCallback</li><li>bottomReachedCallback</li><li>reDrawDOM</li><li>updateTopBottomPaddings</li></ol><pre>  // When top of list is reached<br>  const topReachedCallback = useCallback(<br>    (entry) =&gt; {<br>      if (currentIndex.current === 0) {<br>        const container = document.querySelector(&quot;.box-list&quot;);<br>        container.style.paddingTop = &quot;0px&quot;;<br>        container.style.paddingBottom = &quot;0px&quot;;<br>      }<br>      if (entry.isIntersecting &amp;&amp; currentIndex.current !== 0) {<br>        const firstIndex = getVirtualScrollArea(false);<br>        updateTopBottomPaddings(false);<br>        reDrawDOM(firstIndex);<br>        currentIndex.current = firstIndex;<br>      }<br>    },<br>    [updateTopBottomPaddings, reDrawDOM]<br>  );<br><br>  // When bottom of list is reached<br>  const bottomReachedCallback = useCallback(<br>    (entry) =&gt; {<br>      if (currentIndex.current === maxItemCount - domPageSize) {<br>        return;<br>      }<br>      if (entry.isIntersecting) {<br>        const firstIndex = getVirtualScrollArea(true);<br>        if (list[firstIndex + chunkSize]) {<br>          currentIndex.current = firstIndex;<br>          updateTopBottomPaddings(true);<br>          reDrawDOM(firstIndex);<br>        } else {<br>          if (hasMore) {<br>            setPage((pg) =&gt; pg + 1);<br>            return;<br>          }<br>        }<br>      }<br>    },<br>    [updateTopBottomPaddings, hasMore, maxItemCount, reDrawDOM, list]<br>  );<br><br>  // Top element that act as triggers for initiating changes<br>  const topWatcherElmRef = useCallback(<br>    (node) =&gt; {<br>      if (startElmObserver.current) startElmObserver.current.disconnect();<br>      startElmObserver.current = new IntersectionObserver((entries) =&gt; {<br>        topReachedCallback(entries[0]);<br>      });<br>      if (node) startElmObserver.current.observe(node);<br>    },<br>    [topReachedCallback]<br>  );<br><br>  // Bottom element that act as triggers for initiating changes<br>  const bottomWatcherElmRef = useCallback(<br>    (node) =&gt; {<br>      if (lastElmObserver.current) lastElmObserver.current.disconnect();<br>      lastElmObserver.current = new IntersectionObserver((entries) =&gt; {<br>        bottomReachedCallback(entries[0]);<br>      });<br>      if (node) lastElmObserver.current.observe(node);<br>    },<br>    [bottomReachedCallback]<br>  );</pre><p>topWatcherElmRef and bottomWatcherElmRef will point to the top and bottom elements of our list, respectively. They will be used to set up observers for both elements. The callbacks, topReachedCallback and bottomReachedCallback, will be executed whenever the watchers intersect the current viewport.</p><pre>  // Append next elements to list<br>  const reDrawDOM = useCallback(<br>    (firstIndex) =&gt; {<br>      const items = [];<br>      for (let i = 0; i &lt; domPageSize; i++) {<br>        if (list[i + firstIndex]) {<br>          items.push(list[i + firstIndex]);<br>        }<br>      }<br>      setListItems([...items]);<br>    },<br>    [list]<br>  );</pre><p>The <strong>reDrawDOM</strong> function is utilized to recycle existing DOM nodes. Depending on your requirements, you may need to make modifications or even force a fresh render on specific elements. Nevertheless, the crucial aspect to remember is that we are only replacing content, not entirely mounting or unmounting new elements each time the Sentinels intersect with the root element.</p><pre>  // Update top and bottom pading to virtualize scrolling<br>  const updateTopBottomPaddings = useCallback((isScrollDown) =&gt; {<br>    if (currentIndex.current === 0) {<br>      return;<br>    }<br>    const container = document.querySelector(&quot;.box-list&quot;);<br>    const currentPaddingTop = extractNumber(container.style.paddingTop);<br>    const currentPaddingBottom = extractNumber(container.style.paddingBottom);<br>    const remPaddingsVal = 170 * chunkSize + 10;<br>    if (isScrollDown) {<br>      container.style.paddingTop = currentPaddingTop + remPaddingsVal + &quot;px&quot;;<br>      container.style.paddingBottom =<br>        currentPaddingBottom === 0<br>          ? &quot;0px&quot;<br>          : currentPaddingBottom - remPaddingsVal + &quot;px&quot;;<br>    } else {<br>      container.style.paddingBottom =<br>        currentPaddingBottom + remPaddingsVal + &quot;px&quot;;<br>      container.style.paddingTop =<br>        currentPaddingTop === 0<br>          ? &quot;0px&quot;<br>          : currentPaddingTop - remPaddingsVal + &quot;px&quot;;<br>    }<br>  }, []);</pre><p>The updateTopBottomPaddings method is utilized to obtain new paddings and directly modify the container’s size. This is necessary because, as we recycle our DOM nodes, the actual content remains fixed with a specific number of elements. By expanding the paddings in both directions, we simulate the list extending larger or becoming smaller as we scroll up and down, precisely by the same amount as the heights of the items being removed.</p><p>In certain scenarios, we may also need to calculate and cache the heights of the elements being removed to add paddings accordingly. For our demonstration’s convenience, each row’s height is set to 140px, with a margin of 10px at the top and bottom. Consequently, we are removing and adding (140 + 10 + 10) * the number of items being removed on scrolling</p><h3>Add-On: Collapsible Headers on Scroll</h3><p>So far, we have covered infinite scroll most optimally. However, what if we also want the header elements to collapse when the user starts scrolling down, to increase the screen size for the viewers? Conversely, when the user starts scrolling up, the headers should become visible again, making filters and similar features easily accessible to the user just like most e-commerce platforms do on mobile devices. We successfully implemented this feature in <a href="https://bharatpe.com/">BharatPe’s</a> Loyalty App — <a href="https://zillionrewards.in/">Zillion</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*A40Fyl0NrxcbXqks1eyz1w.gif" /></figure><h3>Mechanism:</h3><p>When the user starts scrolling down, we detect the scroll direction and calculate the offset. Using this information, we gradually collapse the header DOM element pixel by pixel. The headers are stacked on top of each other, creating a visually pleasing effect. For instance, if there are three header elements, and we have set two of them as collapsible, these two headers will move below the third one. However, if all three headers are set as collapsible, they will all stack above the viewport, becoming invisible to the user.</p><p>Conversely, when the user starts scrolling up, we once again capture the scroll direction and offset. Utilizing this data, we begin to unstack the header elements in the same order in which they collapsed. As a result, the headers become visible again, and the user can easily access filters and other features. This dynamic collapsing and uncollapsing of headers enhance the user experience, providing more screen space when needed and re-displaying the headers as the user scrolls back up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*wwR4r954rY74FBxnPPhMaQ.gif" /></figure><blockquote>As you can see, the header elements are translated on the y-axis and move out of sight as the user scrolls through the list.</blockquote><p>Let’s check out the above mechanism in the code</p><p>We have created a useScrollDirection hook, which we use to get scroll direction and scroll offset</p><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>function useScrollDirection(element) {<br>  const [scrollOffset, setScrollOffset] = useState(0);<br>  const [lastScroll, setLastScroll] = useState(0);<br>  const [scrollDirection, setScrollDirection] = useState(&quot;UP&quot;);<br><br>  useEffect(() =&gt; {<br>    let updateScrollDirection = () =&gt; {<br>      /**/<br>    };<br>    let lastScrollY = 0;<br>    if (element &amp;&amp; element.addEventListener) {<br>      lastScrollY = element.scrollTop;<br>      updateScrollDirection = () =&gt; {<br>        const scrollY = element.scrollTop;<br>        const direction = scrollY &gt; lastScrollY ? &quot;DOWN&quot; : &quot;UP&quot;;<br><br>        if (<br>          direction !== scrollDirection &amp;&amp;<br>          (scrollY - lastScrollY &gt; 0 || scrollY - lastScrollY &lt; 0)<br>        ) {<br>          setScrollDirection(direction);<br>        }<br>        setLastScroll(lastScrollY);<br>        setScrollOffset(scrollY);<br>        lastScrollY = scrollY &gt; 0 ? scrollY : 0;<br>      };<br>      element.addEventListener(&quot;scroll&quot;, updateScrollDirection);<br>    }<br>    return () =&gt; {<br>      if (element &amp;&amp; element.removeEventListener) {<br>        element.removeEventListener(&quot;scroll&quot;, updateScrollDirection);<br>      }<br>    };<br>  }, [scrollDirection, element]);<br><br>  return {<br>    scrollDirection,<br>    scrollOffset,<br>    lastScroll<br>  };<br>}<br><br>export default useScrollDirection;</pre><p>Initially, the HeaderElements component creates a reference for each header element. Then, it calculates the height of each header element. Using this height information, the component positions each header at its correct place by assigning the translateY() property. For example, if there are three header elements with heights of 40px, 50px, and 60px respectively, the positioning would be as follows:</p><ul><li>Header element 1: transform: translateY(0px)</li><li>Header element 2: transform: translateY(40px) (height of header 1)</li><li>Header element 3: transform: translateY(90px) (sum of heights of header 1 and header 2)</li></ul><pre>  useEffect(() =&gt; {<br>    let ht = -1;<br>    const offSets = [];<br>    const tys2 = [];<br>    if (headerElements &amp;&amp; headerElements.length) {<br>      headerElements.forEach((_data, index) =&gt; {<br>        tys2.push(0);<br>        const htmlElement = getElement(index);<br>        if (htmlElement) {<br>          if (ht &lt; 0 &amp;&amp; htmlElement[&quot;clientHeight&quot;]) {<br>            ht = 0;<br>          }<br>          ht = ht + htmlElement[&quot;clientHeight&quot;];<br>        }<br><br>        let htt = 0;<br>        for (let i = 0; i &lt; index; i++) {<br>          const htmlElement = getElement(i);<br>          if (htmlElement &amp;&amp; headerElements[i].collapse) {<br>            htt = htt + htmlElement[&quot;clientHeight&quot;] || 0;<br>          }<br>        }<br>        offSets.push(htt);<br>      });<br>    }<br>    setTopPadding(ht);<br>    setTransformOffSets(offSets);<br>    setTYS(tys2);<br>    setHeaderHeight(ht);<br>  }, [headerElements, setTopPadding]);<br><br>  return (<br>    &lt;&gt;<br>      {headerElements &amp;&amp; headerElements.length ? (<br>        &lt;div<br>          ref={headRef}<br>          className=&quot;header-wraper&quot;<br>          style={{<br>            height: `${headerHeight}px`,<br>            zIndex: headerElements.length + 1<br>          }}<br>        &gt;<br>          {headerElements.map((data, index) =&gt; (<br>            &lt;div<br>              key={index}<br>              className=&quot;header&quot;<br>              ref={(element) =&gt; (headerRef.current[index] = element)}<br>              style={{<br>                zIndex: headerElements.length - index,<br>                transform: `translateY(${tys[index]}px)`,<br>                backgroundColor: data.backgroundColor,<br>                position: &quot;relative&quot;<br>              }}<br>            &gt;<br>              {data.content}<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      ) : null}<br>    &lt;/&gt;<br>  );</pre><p>Once the user starts scrolling, the system will detect the change, and the header elements will be dynamically updated accordingly. This will cause the headers to either collapse or become visible based on the direction of the scroll. For example, if the user scrolls down 40 px then if header elements will have translateY as follows:</p><ul><li>Header element 1: transform: translateY(-40px)</li><li>Header element 2: transform: translateY(0px)</li><li>Header element 3: transform: translateY(50px)</li></ul><p>Hiding header element 1 from the user’s view.</p><pre>  useEffect(() =&gt; {<br>    let nch = 0;<br>    let ch = 0;<br>    headerElements.forEach((data, i) =&gt; {<br>      const htmlElement = getElement(i);<br>      let val = undefined;<br>      if (htmlElement) {<br>        const offset = transformOffSets[i];<br>        const th = offset + (htmlElement[&quot;clientHeight&quot;] || 0);<br>        const style = window.getComputedStyle(htmlElement);<br>        const matrix = new DOMMatrixReadOnly(style.transform);<br>        const prevTyVal = matrix.m42;<br>        if (scrollDirection === &quot;DOWN&quot;) {<br>          if (data.collapse) {<br>            if (Math.abs(prevTyVal) &lt; Math.abs(th)) {<br>              const actualO = lastScroll - scrollOffset;<br>              if (prevTyVal + actualO &lt; -th) {<br>                val = -th;<br>              } else {<br>                val = prevTyVal + actualO;<br>              }<br>            }<br>          } else {<br>            if (Math.abs(prevTyVal) &lt; Math.abs(offset)) {<br>              const actualO = lastScroll - scrollOffset;<br>              if (prevTyVal + actualO &lt; -offset) {<br>                val = -offset;<br>              } else {<br>                val = prevTyVal + actualO;<br>              }<br>            }<br>          }<br>        } else if (scrollDirection === &quot;UP&quot;) {<br>          if (lastScroll &gt;= scrollOffset) {<br>            const actualO = lastScroll - scrollOffset;<br>            if (prevTyVal + actualO &gt; 0) {<br>              val = 0;<br>            } else {<br>              val = prevTyVal + actualO;<br>            }<br>          } else {<br>            val = 0;<br>          }<br>        }<br>        if (!data.collapse) {<br>          nch = nch + htmlElement[&quot;clientHeight&quot;] || 0;<br>        } else {<br>          ch = ch + htmlElement[&quot;clientHeight&quot;] || 0;<br>        }<br>      } else {<br>        val = 0;<br>      }<br>      if (val !== undefined) {<br>        setTYS((ty) =&gt; {<br>          ty[i] = val;<br>          return [...ty];<br>        });<br>      }<br>    });<br><br>    if (headRef &amp;&amp; headRef.current) {<br>      const th = nch + ch;<br>      const prevH = headRef.current[&quot;clientHeight&quot;] || 0;<br>      if (scrollDirection === &quot;DOWN&quot;) {<br>        if (prevH &gt; nch) {<br>          const actualO = lastScroll - scrollOffset;<br>          if (prevH + actualO &lt; nch) {<br>            setHeaderHeight(nch);<br>          } else {<br>            setHeaderHeight((ht) =&gt; {<br>              ht = prevH + actualO;<br>              return ht;<br>            });<br>          }<br>        }<br>      } else if (scrollDirection === &quot;UP&quot;) {<br>        const actualO = lastScroll - scrollOffset;<br>        if (lastScroll &gt;= scrollOffset) {<br>          if (prevH + actualO &gt;= th) {<br>            setHeaderHeight(th);<br>          } else {<br>            setHeaderHeight((ht) =&gt; {<br>              ht = prevH + actualO;<br>              return ht;<br>            });<br>          }<br>        } else {<br>          setHeaderHeight(th);<br>        }<br>      }<br>    }<br>  }, [<br>    scrollDirection,<br>    headerElements,<br>    scrollOffset,<br>    lastScroll,<br>    transformOffSets<br>  ]);</pre><h3>Conclusion:</h3><p>Developing a high-performance infinite scroll feature can be challenging, but the Intersection Observer API makes it achievable and efficient. Aside from infinite scrolling, Intersection Observer can also be utilized for lazy loading images, running animations, and various other tasks. Please feel free to test the complete demo on CodeSandbox given below and share your feedback with us!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Finfinite-scroll-n5pv6w&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Finfinite-scroll-n5pv6w&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fn5pv6w%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/430043fe80f4609c0d2a1a25103d0714/href">https://medium.com/media/430043fe80f4609c0d2a1a25103d0714/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11420189ebe" width="1" height="1" alt=""><hr><p><a href="https://engineering.bharatpe.com/supercharge-your-reactjs-app-with-optimized-infinite-scrolling-c11420189ebe">Supercharge Your ReactJS App with Optimized Infinite Scrolling</a> was originally published in <a href="https://engineering.bharatpe.com/">BharatPe Tech Chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>