<?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 Manpreetkamboj on Medium]]></title>
        <description><![CDATA[Stories by Manpreetkamboj on Medium]]></description>
        <link>https://medium.com/@manpreetkamboj6191?source=rss-818177f3e9f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L8fmGwCmpUrJT2sw</url>
            <title>Stories by Manpreetkamboj on Medium</title>
            <link>https://medium.com/@manpreetkamboj6191?source=rss-818177f3e9f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 26 May 2026 10:41:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manpreetkamboj6191/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[SSR vs CSR in React: A Practical Comparison]]></title>
            <link>https://medium.com/@manpreetkamboj6191/ssr-vs-csr-in-react-a-practical-comparison-e81c7135a4c7?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e81c7135a4c7</guid>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Sun, 10 May 2026 12:30:30 GMT</pubDate>
            <atom:updated>2026-05-10T12:38:08.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mXniCQK_Yh4_A7_VNa7mQ.png" /></figure><h3>Understanding Server-Side Rendering (SSR) vs Client-Side Rendering (CSR)</h3><p>When building React applications, one of the fundamental decisions you’ll make is <strong>how</strong> your content gets rendered. Should it happen on the server or in the browser? Let’s explore both approaches with practical examples.</p><h4>What is CSR (Client-Side Rendering)?</h4><p>Client-Side Rendering means React runs <strong>entirely in the browser</strong>. The server sends a minimal HTML file with a JavaScript bundle, and React renders everything on the client.</p><p><strong>Example — CSR App:</strong></p><pre>export default function App() {<br>  return (<br>    &lt;main className=&quot;app-shell&quot;&gt;<br>      &lt;h1&gt;React CSR Example&lt;/h1&gt;<br>      &lt;p&gt;This page is rendered entirely on the client using React.&lt;/p&gt;<br>      &lt;button onClick={() =&gt; alert(&#39;Client-side React is active!&#39;)}&gt;<br>        Click me<br>      &lt;/button&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><p><strong>When you load this page:</strong></p><ol><li>Browser receives blank HTML: &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</li><li>JavaScript bundle downloads</li><li><strong>White screen appears</strong> ← user sees nothing</li><li>React renders the content</li><li>Page becomes interactive</li></ol><p><strong>Pros:</strong></p><ul><li>Fast subsequent navigation (SPA)</li><li>Rich interactivity</li><li>Simpler server requirements</li></ul><p><strong>Cons:</strong></p><ul><li>Slow First Contentful Paint (FCP)</li><li>Poor SEO (search engines see blank page)</li><li>Large JavaScript bundle</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnRoXABtH0Wp3KDZjiAzlQ.png" /></figure><h3>CSR Flow Analysis &amp; Improvement</h3><h3>Current CSR Flow Issue</h3><p>You’re seeing an empty &lt;div id=&quot;root&quot;&gt;&lt;/div&gt; because the JavaScript bundle hasn&#39;t loaded yet.</p><p><strong>Current flow:</strong></p><ol><li>Browser requests <a href="http://localhost:4174">http://localhost:417</a>3</li><li>Server sends index.html with empty root div</li><li>White screen appears ⏳</li><li>Browser downloads index-CvKRpKXl.js</li><li>React renders into #root</li><li>Page becomes visible</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0H6msW80dlPviR072RTZUA.gif" /></figure><p>Blank white screen displays during client-side image rendering.</p><h4>What is SSR (Server-Side Rendering)?</h4><p>Server-Side Rendering means React runs <strong>on the server</strong>, generates HTML, and sends it to the browser. The browser receives <strong>ready-to-display</strong> content immediately.</p><p><strong>Example — SSR App:</strong></p><pre>import &#39;./style.css&#39;<br><br>export default function App() {<br>  return (<br>    &lt;main className=&quot;app-shell&quot;&gt;<br>      &lt;h1&gt;React SSR Example&lt;/h1&gt;<br>      &lt;p&gt;This page is rendered on the server and hydrated on the client.&lt;/p&gt;<br>      &lt;button onClick={() =&gt; alert(&#39;Client hydration works!&#39;)}&gt;<br>        Click me<br>      &lt;/button&gt;<br>    &lt;/main&gt;<br>  )<br>}<br></pre><p><strong>Server-side (</strong><strong>entry-server.jsx):</strong></p><pre>import { renderToString } from &#39;react-dom/server&#39;<br>import App from &#39;./App&#39;<br><br>export function render() {<br>  return renderToString(&lt;App /&gt;)<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jFoduH1Z6yeMiO-J6jOJA.png" /></figure><p>In Server-Side Rendering (SSR), the server generates the full HTML for a page before sending it to the browser. This makes better for SEO.</p><p><strong>When you load this page:</strong></p><ol><li>Server renders React to HTML string</li><li>Browser receives <strong>full HTML content immediately</strong> ← instant display</li><li>JavaScript bundle downloads in background</li><li>React hydrates the page (attaches listeners)</li><li>Page becomes interactive</li></ol><p><strong>Pros:</strong></p><ul><li>Fast First Contentful Paint (FCP) ✅</li><li>Better SEO (search engines see full HTML)</li><li>Smaller initial JavaScript</li></ul><p><strong>Cons:</strong></p><ul><li>Slower server response time</li><li>More server resources needed</li><li>Complex setup</li></ul><p><strong>What is Hydration?</strong></p><p>Hydration means making a webpage interactive after it loads.</p><p>In SSR, the server sends the page HTML first, so users can see the content quickly.</p><p>But initially:</p><ul><li>Buttons do not work</li><li>Click events do not work</li><li>React is not active yet</li></ul><p>After JavaScript loads, React connects everything and makes the page interactive.</p><p>That process is called <strong>Hydration</strong>.</p><h4>When to Use Each?</h4><p><strong>Use CSR when:</strong></p><ul><li>Building internal dashboards (SEO doesn’t matter)</li><li>Users have fast internet</li><li>You prioritize developer experience</li><li>Real-time updates are critical</li></ul><p><strong>Use SSR when:</strong></p><ul><li>SEO is important (blogs, e-commerce, marketing sites)</li><li>You need fast First Contentful Paint</li><li>Users have slow networks</li><li>You can handle server complexity</li></ul><p><strong>Conclusion:</strong> SSR and CSR aren’t competing approaches — they solve different problems. Choose based on your users, content type, and infrastructure.</p><p>Source Code:<a href="https://github.com/manpreet1719/React-Learning">https://github.com/manpreet1719/React-Learning</a><br>LinkedIn:<a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e81c7135a4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Flying Emojis in React.]]></title>
            <link>https://medium.com/@manpreetkamboj6191/implementing-flying-emojis-in-react-7a9ae55d0ec9?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9ae55d0ec9</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 09:50:18 GMT</pubDate>
            <atom:updated>2024-04-30T09:50:18.320Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog , we’ll explore how to implement flying emojis in a React application. You’ve likely encountered emojis flying around in chats and various other places, adding a dynamic and engaging element to the user experience. Let’s dive into how we can bring this fun feature to life using React!</p><p><strong>Below is the UI implementation in React. Take a look at the code provided to see how the user interface is structured and styled within a React application.</strong></p><pre>&lt;div style={{<br>                position: &#39;absolute&#39;,<br>                left: &#39;50%&#39;,<br>                bottom: &#39;60px&#39;,<br>                fontSize: &#39;48px&#39;,<br>                lineHeight: &#39;1&#39;,<br>                width: &#39;48px&#39;,<br>                height: &#39;48px&#39;<br>            }} onClick={() =&gt; handleDisplayFlyingEmoji(&#39;fire&#39;)}&gt;<br>                🔥&lt;/div&gt;<br>            &lt;div className=&quot;flying-emojis&quot; ref={overlayRef}&gt;<br>                &lt;style&gt;<br>                    {`<br>        .flying-emojis {<br>          backgroundColor:red;<br>          position: fixed;<br>          top: 0px;<br>          bottom: 0px;<br>          left: 0px;<br>          right: 0px;<br>          overflow: hidden;<br>          pointer-events: none;<br>          user-select: none;<br>          z-index: 99;<br>        }<br><br>        .flying-emojis .emoji {<br>          position: absolute;<br>          left: 50%;<br>          bottom: 60px;<br>          font-size: 48px;<br>          line-height: 1;<br>          width: 48px;<br>          height: 48px;<br>        }<br><br>        .flying-emojis .emoji.wiggle-1 {<br>          animation: emerge 3s forwards, wiggle-1 1s ease-in-out infinite alternate;<br>        }<br><br><br>        @keyframes emerge {<br>          to {<br>            bottom: 85%;<br>            opacity: 0;<br>          }<br>        }<br><br>        @keyframes wiggle-1 {<br>          from {<br>            margin-left: -20px;<br>          }<br>          to {<br>            margin-left: 50px;<br>          }<br>        }<br>      `}<br>                &lt;/style&gt;<br>            &lt;/div&gt;</pre><p><strong>Let me explain the animation in that are used —</strong></p><pre>.flying-emojis .emoji.wiggle-1 {<br>          animation: emerge 3s forwards, wiggle-1 1s ease-in-out infinite alternate;<br>        }<br><br>        @keyframes emerge {<br>          to {<br>            bottom: 85%;<br>            opacity: 0;<br>          }<br>        }<br><br>        @keyframes wiggle-1 {<br>          from {<br>            margin-left: -20px;<br>          }<br>          to {<br>            margin-left: 50px;<br>          }<br>        }</pre><ol><li>animation: emerge 3s forwards, wiggle-1 1s ease-in-out infinite alternate;: This line sets up two animations for the selected elements. The first animation is called emerge, which lasts for 3 seconds and moves the emojis upwards and fades them out. The second animation is called wiggle-1, which lasts for 1 second, wiggles the emojis back and forth, and repeats infinitely in an alternate direction.</li><li>@keyframes emerge: This defines the emerge animation. It starts with the emojis at their original position and ends with them moving up to 85% of the container&#39;s height and fading out completely.</li><li>@keyframes wiggle-1: This defines the wiggle-1 animation. It starts with the emojis having a margin-left of -20 pixels (which means they are shifted 20 pixels to the left from their original position), and ends with them having a margin-left of 50 pixels (which means they are shifted 50 pixels to the right from their original position). This creates a wiggling effect as they move back and forth.</li></ol><p><strong>Let’s make the animation work.</strong></p><pre>const handleRemoveFlyingEmoji = useCallback((node) =&gt; {<br>        if (!overlayRef.current) return;<br>        overlayRef.current.removeChild(node);<br>    }, []);<br><br><br>const handleDisplayFlyingEmoji = useCallback(<br>        (emoji) =&gt; {<br>            console.log(emoji);<br>            if (!overlayRef.current) {<br>                return;<br>            }<br><br>            console.log(`⭐ Displaying flying emoji: ${emoji}`);<br><br>            const node = document.createElement(&#39;div&#39;);<br>            node.appendChild(document.createTextNode(EMOJI_MAP[emoji]));<br>            node.className = &#39;emoji wiggle-1&#39;<br>            node.style.transform = `rotate(${-30 + Math.random() * 60}deg)`;<br>            overlayRef.current.appendChild(node);<br><br>            node.addEventListener(&#39;animationend&#39;, (e) =&gt; {<br>                console.log(&quot;removed&quot;)<br>                handleRemoveFlyingEmoji(e.target)<br>            });<br>        },<br>        [handleRemoveFlyingEmoji]<br>    );</pre><p>The function handleDisplayFlyingEmoji is used to create a div element, apply a classname, transformation, and then append it to the parent div element. Additionally, it adds an event listener for the &#39;animationed&#39; event, which helps in removing the created element from the DOM.</p><p>The useCallback hook is employed to prevent the creation of a new function instance on each rendering.</p><p><strong>Avoiding Memory Leaks —</strong></p><pre>    // Remove all event listeners on unmount to prevent console warnings<br>    useEffect(() =&gt; {<br>        return () =&gt; {<br>            if (overlayRef.current) {<br>                console.log(&quot;Unmounted&quot;);<br>                overlayRef.current?.childNodes.forEach((n) =&gt; {<br>                    n.removeEventListener(&#39;animationend&#39;, handleRemoveFlyingEmoji);<br>                });<br>            }<br>        };<br>    }, []);</pre><p>It helps us remove the event listener to prevent memory leaks.</p><p><strong>Here’s the entire code combined —</strong></p><pre>import React, { useEffect, useRef, useCallback } from &#39;react&#39;;<br><br>const EMOJI_MAP = {<br>    fire: &#39;🔥&#39;,<br>}<br><br><br>export const FlyingEmoji = () =&gt; {<br><br>    const overlayRef = useRef();<br><br>    const handleRemoveFlyingEmoji = useCallback((node) =&gt; {<br>        if (!overlayRef.current) return;<br>        overlayRef.current.removeChild(node);<br>    }, []);<br><br><br><br>    const handleDisplayFlyingEmoji = useCallback(<br>        (emoji) =&gt; {<br>            console.log(emoji);<br>            if (!overlayRef.current) {<br>                return;<br>            }<br><br>            console.log(`⭐ Displaying flying emoji: ${emoji}`);<br><br>            const node = document.createElement(&#39;div&#39;);<br>            node.appendChild(document.createTextNode(EMOJI_MAP[emoji]));<br>            node.className = &#39;emoji wiggle-1&#39;<br>            node.style.transform = `rotate(${-30 + Math.random() * 60}deg)`;<br>            overlayRef.current.appendChild(node);<br><br>            node.addEventListener(&#39;animationend&#39;, (e) =&gt; {<br>                console.log(&quot;removed&quot;)<br>                handleRemoveFlyingEmoji(e.target)<br>            });<br>        },<br>        [handleRemoveFlyingEmoji]<br>    );<br><br><br>    // Remove all event listeners on unmount to prevent console warnings<br>    useEffect(() =&gt; {<br>        return () =&gt; {<br>            if (overlayRef.current) {<br>                console.log(&quot;Unmounted&quot;);<br>                overlayRef.current?.childNodes.forEach((n) =&gt; {<br>                    n.removeEventListener(&#39;animationend&#39;, handleRemoveFlyingEmoji);<br>                });<br>            }<br>        };<br>    }, []);<br><br><br>    return (<br>        &lt;&gt;<br>            &lt;div style={{<br>                position: &#39;absolute&#39;,<br>                left: &#39;50%&#39;,<br>                bottom: &#39;60px&#39;,<br>                fontSize: &#39;48px&#39;,<br>                lineHeight: &#39;1&#39;,<br>                width: &#39;48px&#39;,<br>                height: &#39;48px&#39;<br>            }} onClick={() =&gt; handleDisplayFlyingEmoji(&#39;fire&#39;)}&gt;<br>                🔥&lt;/div&gt;<br>            &lt;div className=&quot;flying-emojis&quot; ref={overlayRef}&gt;<br>                &lt;style&gt;<br>                    {`<br>        .flying-emojis {<br>          backgroundColor:red;<br>          position: fixed;<br>          top: 0px;<br>          bottom: 0px;<br>          left: 0px;<br>          right: 0px;<br>          overflow: hidden;<br>          pointer-events: none;<br>          user-select: none;<br>          z-index: 99;<br>        }<br><br>        .flying-emojis .emoji {<br>          position: absolute;<br>          left: 50%;<br>          bottom: 60px;<br>          font-size: 48px;<br>          line-height: 1;<br>          width: 48px;<br>          height: 48px;<br>        }<br><br>        .flying-emojis .emoji.wiggle-1 {<br>          animation: emerge 3s forwards, wiggle-1 1s ease-in-out infinite alternate;<br>        }<br><br><br>        @keyframes emerge {<br>          to {<br>            bottom: 85%;<br>            opacity: 0;<br>          }<br>        }<br><br>        @keyframes wiggle-1 {<br>          from {<br>            margin-left: -20px;<br>          }<br>          to {<br>            margin-left: 50px;<br>          }<br>        }<br>      `}<br>                &lt;/style&gt;<br>            &lt;/div&gt;<br>        &lt;/&gt;<br><br>    );<br>};<br><br>export default FlyingEmoji;</pre><p><strong>Final output —</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*IHVyWw4z3JbvH48PS0AfcQ.gif" /></figure><p>So that’s how you implement flying emojis! Thank you.</p><p>Linkedin — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9ae55d0ec9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infinite Scrolling in React]]></title>
            <link>https://medium.com/@manpreetkamboj6191/infinite-scrolling-in-react-674dde144382?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/674dde144382</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 12:41:46 GMT</pubDate>
            <atom:updated>2024-04-28T12:48:07.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*BXh3ULyI9Jp-jph5iyMewA.png" /></figure><p>In this blog post, we’ll dive into implementing infinite scrolling, enhancing the user experience along the way. Let’s outline the states to this implementation:</p><ul><li>items: Holds the list of items to display.</li><li>loading: Signals when the user reaches the bottom of the screen, indicating the need to load more items.</li><li>page: Facilitates making API calls as the user scrolls to the bottom, incrementing the page number accordingly.</li><li>hasmore: Indicates whether additional data is available.</li></ul><p>Code for these States</p><pre> const [items, setItems] = useState([]);<br> const [loading, setLoading] = useState(false);<br> const [page, setPage] = useState(1);<br> const [hasmore, setHasMore] = useState(true);</pre><p>I haveimplemented a fetchData function to facilitate API calls and manage the data retrieval process. This function plays a crucial role in fetching the necessary items from the server and updating the UI accordingly.</p><pre>  const fetchData = async () =&gt; {<br> <br>        if (loading &amp;&amp; !hasmore) return;<br><br>        setLoading(true);<br><br>        try {<br>            let res = await fetch(`https://dummyjson.com/products?limit=10&amp;skip=${(page - 1) * 10}`);<br>            let data = await res.json();<br>            setItems((prevItems) =&gt; [...prevItems, ...data.products]);<br>            data.products.length &gt; 0 ? setHasMore(true) : setHasMore(false);<br>            setLoading(false);<br>        } catch (err) {<br>            console.log(err);<br>            setLoading(false);<br>        };<br>    }<br><br>    useEffect(()=&gt; {<br>        if(hasmore){<br>            fetchData();<br>        }<br>        <br>    },[page])</pre><p>Using the dummyjson api for fetching the data</p><p>Certainly! In JavaScript, when dealing with scrolling behavior, understanding the properties scrollTop, clientHeight, and scrollHeight is crucial.</p><ul><li>scrollTop: This property represents the vertical scroll position of an element. It indicates how far the top of the content is scrolled from the top of its container. If the element is at the top of the scrollable area, scrollTop is 0.</li><li>clientHeight: It represents the height of the viewport or the visible content area of an element. In the context of scrolling, it signifies the height of the portion of the element’s content that is currently visible to the user without scrolling.</li><li>scrollHeight: This property represents the total height of an element’s content, including content not visible on the screen due to overflow. It essentially represents the entire height of the content, both visible and hidden.</li></ul><p>In the handleScroll function provided, these properties are utilized to detect when the user has scrolled to the bottom of the page. When scrollTop + clientHeight equals or exceeds scrollHeight, it indicates that the user has reached the bottom, prompting further action, such as loading more content or triggering an API call to fetch additional data.</p><p>Utilizing the useEffect hook, we can efficiently manage a scroll event listener, ensuring it&#39;s activated when the component mounts and removed upon unmounting. This approach enhances code organization and prevents memory leaks.</p><pre>   const handleScroll = () =&gt; {<br>        const { scrollTop, clientHeight, scrollHeight } =<br>            document.documentElement;<br>        if (scrollTop + clientHeight &gt;= scrollHeight) {<br>           <br>            setPage((prevPage) =&gt; prevPage + 1);<br><br>        }<br>    }<br><br>    useEffect(() =&gt; {<br>        window.addEventListener(&#39;scroll&#39;, handleScroll);<br>        return () =&gt; window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    }, []);</pre><p>Let’s review the implementation of the InfiniteScroll component code together.</p><pre>import { useEffect, useState, useCallback } from &quot;react&quot;<br><br>const InfiniteScroll = () =&gt; {<br><br>    const [items, setItems] = useState([]);<br>    const [loading, setLoading] = useState(false);<br>    const [page, setPage] = useState(1);<br>    const [hasmore, setHasMore] = useState(true);<br><br><br><br>    const fetchData = async () =&gt; {<br>        <br>        if (loading &amp;&amp; !hasmore) return;<br><br>        setLoading(true);<br><br>        try {<br>            <br>            let res = await fetch(`https://dummyjson.com/products?limit=10&amp;skip=${(page - 1) * 10}`);<br>            let data = await res.json();<br>            setItems((prevItems) =&gt; [...prevItems, ...data.products]);<br>            data.products.length &gt; 0 ? setHasMore(true) : setHasMore(false);<br>            setLoading(false);<br>        } catch (err) {<br>            console.log(err);<br>            setLoading(false);<br>        };<br>    }<br><br>    const handleScroll = () =&gt; {<br>        const { scrollTop, clientHeight, scrollHeight } =<br>            document.documentElement;<br>        if (scrollTop + clientHeight &gt;= scrollHeight) {<br>           <br>            setPage((prevPage) =&gt; prevPage + 1);<br><br>        }<br>    }<br>    useEffect(()=&gt; {<br>        if(hasmore){<br>            fetchData();<br>        }<br>        <br>    },[page])<br><br>    useEffect(() =&gt; {<br>        window.addEventListener(&#39;scroll&#39;, handleScroll);<br>        return () =&gt; window.removeEventListener(&#39;scroll&#39;, handleScroll);<br>    }, []);<br><br><br>    return (<br>        &lt;div&gt;<br>            &lt;ul &gt;<br>                {items.map((item, index) =&gt; (<br>                    &lt;li style={{height:&#39;200px&#39;, border:&#39;2px solid black&#39;, marginBottom : &#39;10px&#39;}} key={index}&gt;{item.title}&lt;/li&gt;<br>                ))}<br>            &lt;/ul&gt;<br>            {loading &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>            {!hasmore  &amp;&amp; &lt;p&gt;No More data ......&lt;/p&gt;}<br>        &lt;/div&gt;<br>    )<br><br>}<br><br>export default InfiniteScroll</pre><p>In this explanation of Infinite Scrolling, we can enhance our approach by tapping into optimization potential through the implementation of a Custom Hook and design patterns. Suggestions and enhancements to the code are warmly welcomed to ensure performance and maintainability.</p><p>linkedin — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674dde144382" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Design Pattern in Java]]></title>
            <link>https://medium.com/@manpreetkamboj6191/singleton-design-pattern-in-java-0c1a51fb0fd0?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c1a51fb0fd0</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 08:49:41 GMT</pubDate>
            <atom:updated>2023-11-01T08:49:41.728Z</atom:updated>
            <content:encoded><![CDATA[<p>The Singleton design pattern is used to ensure that a single instance of a class is maintained and made available consistently across the entire application.</p><p>Let’s explore how to implement the Singleton Design pattern.</p><p><strong>1 Step : Adding Private Constructor</strong></p><p>By including a private constructor within the class, you can prevent users from creating new instances of the class.</p><pre>public class Singleton {<br>    <br>    // making Constructor as private.<br>    private Singleton(){}<br><br>}</pre><p><strong>2 Step: Adding static instance</strong></p><p>Now we are declaring a static instance of Class and static method to get the required instance .You might be wondering why the use of static is crucial in this context .<br>This is because a variable declared with the ‘static’ keyword is shared across all objects of the class, and a ‘static’ method is used to access the static <em>instance </em>of the class.</p><pre>public class Singleton {<br><br>    //declaring static instance of Class.<br>    public static  Singleton instance;<br><br><br>    private Singleton(){}<br><br>   //adding a static method to get required instance<br>    public static Singleton getInstance(){<br>        if(instance == null){<br>             instance = new Singleton();<br>        }<br>        return instance;<br>    }<br><br><br>}</pre><p>Inside the getInstance() method, it first checks if an instance of the class exists. If it doesn&#39;t, a new instance is created, otherwise the existing instance is returned.</p><p><strong>Step 3: Using Singleton Class</strong></p><p>Now, you can use the Singleton throughout your application:</p><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        System.out.println(&quot;Singleton pattern in Java&quot;);<br>        System.out.println(Singleton.getInstance());<br>    }<br>}</pre><h3><strong>Implementing Thread Safe Singleton</strong></h3><p>So what is problem in previous Singleton implementation ?</p><p>The Singleton design pattern is used to ensure that a class has only one instance and provides a global point of access to that instance. When dealing with multithreaded applications, it’s possible that multiple threads may try to create instances of the singleton simultaneously. This can lead to multiple instances being created, violating the singleton pattern.</p><p><strong>How to solve this Problem ?</strong></p><p>One way to do this is by using a synchronized block or method. When we use synchronized (Singleton.class), you are synchronizing on the class object itself, which means that only one thread can enter the synchronized block at a time. Here&#39;s an example of how you might implement a thread-safe Singleton pattern using synchronized (Singleton.class)only we have to make changes ingetInstance() method.</p><pre>public static Singleton getInstance(){<br>    if(instance == null){<br>        synchronized (Singleton.class) {<br>            if (instance == null) {<br>                instance = new Singleton();<br>            }<br>        }<br>    }<br>    return instance;<br>}</pre><p>In this code, the synchronized (Singleton.class) block is used to ensure that only one thread can enter it at a time. This is where the instance of the Singleton is created if it doesn&#39;t already exist. This double-checked locking approach helps improve performance by avoiding unnecessary synchronization after the instance has been created.</p><h3>Summary</h3><p>The Singleton Design Pattern ensures that there’s only one instance of a class in your application, promoting resource efficiency and providing global accessibility.</p><p>Follow me — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c1a51fb0fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tic Tac Toe — Low Level Design]]></title>
            <link>https://medium.com/@manpreetkamboj6191/tic-tac-toe-low-level-design-581ed4bb9281?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/581ed4bb9281</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 20:39:06 GMT</pubDate>
            <atom:updated>2023-09-26T20:39:06.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tic Tac Toe — Low Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*9hbI_l8k4xNxAWweEA-FPg.jpeg" /></figure><p>Let’s examine the requirements for a Tic Tac Toe game:</p><ol><li>The game board should be adaptable in size, starting with the standard 3x3 grid but allowing for customization to an ‘n’ size grid.</li><li>The game should support multiple players, with each player having the freedom to select their preferred symbol, which can be ‘X,’ ‘O,’ or any other character.</li><li>The game must provide a mechanism to determine a winner, where one player successfully forms a winning combination, or it should be able to identify a tie when no more moves are possible.</li></ol><p>We are currently looking at these requirements, but we can add more if necessary.</p><p>Let’s think about the entities that will be involved in our game.</p><p>1. Cell -&gt; The smallest unit in the game, representing an individual space on the game board. Each cell can be marked with either an ‘X’ or ‘O,’ denoting the CellType.</p><p>2. Board -&gt; The core entity that comprises a 2D array of cells, forming the playable grid for the game. This board is central to various game operations and interactions.</p><p>3. Player -&gt; An entity that encompasses the player’s name and the chosen symbol (e.g., ‘X’ or ‘O’). Additional attributes can be included as needed.</p><p>4. Game -&gt; Used for Initializing the Game with all its properties.</p><p>Let’s now consider creating a Class Diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqoje1FKZaj-PQ6HZasKGQ.png" /></figure><h3>Cell entity</h3><p>A Cell is responsible for determining the symbol (‘X’ or ‘O’), and it’s further divided into two classes: CellX and CellO, both of which are subclasses of the Cell class means CellX and CellO <strong>is-a</strong> Cell class.</p><pre>public class Cell {<br>   CellType cellType;<br>   Cell(CellType cellType){<br>       this.cellType = cellType;<br>   }<br>}<br>// Cell Class</pre><pre>public class CellX extends Cell{<br>    CellX(){<br>        super(CellType.X);<br>    }<br>}</pre><pre>public class CellO extends  Cell{<br>    CellO(){<br>        super(CellType.O);<br>    }<br>}</pre><p>CellType is a enum used to provide symbols.</p><pre>public enum CellType {<br>    X,<br>    O<br>}</pre><h3><strong>Player entity</strong></h3><pre>public class Player {<br><br>    String name;<br>    Cell cellType;<br>    Player(String name,Cell cellType){<br>        this.name = name;<br>        this.cellType = cellType;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public void setCellType(Cell cellType) {<br>        this.cellType = cellType;<br>    }<br><br>    public Cell getCellType() {<br>        return cellType;<br>    }<br><br>}</pre><p>The Player entity includes a Cell means Player <strong>has-a </strong>Cell , indicating their chosen symbol (‘X’ or ‘O’), and has attributes for their name, along with corresponding getter and setter methods to access and modify name attribute.</p><h3><strong>Board entity</strong></h3><pre><br>public class Board {<br><br>    public int size;<br>    public Cell[][] board;<br>    Board(int size){<br>        this.size = size;<br>        board = new Cell[size][size];<br>    }<br>    boolean getFreeCells(){<br>        for(int i = 0;i&lt;size;i++){<br>            for(int j = 0;j&lt;size;j++){<br>                if(board[i][j] == null){<br>                    return true;<br>                }<br>            }<br>        }<br>        return false;<br>    }<br><br>    boolean addAtPostion(int x,int y,Cell cell){<br>        if(board[x][y] != null){<br>            return false;<br>        }<br>        board[x][y] = cell;<br>        return true;<br>    }<br>    public void printBoard() {<br><br>        for (int i = 0; i &lt; size; i++) {<br>            for (int j = 0; j &lt; size; j++) {<br>                if (board[i][j] != null) {<br>                    System.out.print(board[i][j].cellType.name() + &quot;   &quot;);<br>                } else {<br>                    System.out.print(&quot;    &quot;);<br><br>                }<br>                System.out.print(&quot; | &quot;);<br>            }<br>            System.out.println();<br><br>        }<br>    }<br><br><br><br>}</pre><p>Board is a entity having a Cell means board class <strong>has-a</strong> Cell entity used for creating a 2-D matrix of Cell datatype , having a size which can be added according to our requirement.</p><p>The Board class offers functions like:</p><ul><li>printBoard(): This function displays the current state of the board.</li><li>addAtPosition(): It allows us to place &#39;X&#39; or &#39;O&#39; symbols at specific positions on the board.</li><li>getFreeCells(): This function checks if there are any empty cells left on the board.</li></ul><h3>Game Class</h3><pre>import java.util.*;<br><br>public class Game {<br><br>    Deque&lt;Player&gt; players;<br>    Board gameboard;<br>    Game(){<br>        players = new LinkedList&lt;Player&gt;();<br>        CellX cellX = new CellX();<br>        players.add(new Player(&quot;Player1&quot;,cellX));<br>        CellO cellY = new CellO();<br>        players.add((new Player(&quot;Player2&quot;,cellY)));<br>        gameboard = new Board(3);<br>    }<br>    public String startGame(){<br><br>        boolean isWinner = true;<br>        while(isWinner){<br>            Player playerturn = players.removeFirst();<br>            gameboard.printBoard();<br>            boolean freeCells = gameboard.getFreeCells();<br>            if(!freeCells){<br>                isWinner = false;<br>                continue;<br>            }<br><br>            System.out.print(&quot;Player &quot; + playerturn.getName() + &quot;Enter Position&quot;);<br>            Scanner inputScanner = new Scanner(System.in);<br>            String s = inputScanner.nextLine();<br>            String[] values = s.split(&quot;,&quot;);<br>            int inputRow = Integer.valueOf(values[0]);<br>            int inputColumn = Integer.valueOf(values[1]);<br><br>            boolean isValidPosition = gameboard.addAtPostion(inputRow,inputColumn,playerturn.cellType);<br><br>            if(!isValidPosition){<br>                System.out.print(&quot;Please Enter valid Position&quot;);<br>                players.addFirst(playerturn);<br>                continue;<br>            }<br>            players.addLast(playerturn);<br><br>            boolean iswinner = isWinner(inputRow,inputColumn,playerturn.cellType.cellType);<br>            if(iswinner){<br>                 return playerturn.name;<br>            }<br>        }<br>        return &quot;Match Tie&quot;;<br>    }<br><br>    public boolean isWinner(int row,int column,CellType cellType){<br>        boolean isrow = true;<br>        boolean isColumn = true;<br>        boolean isDiagonal = true;<br>        boolean isAntiDiagonal = true;<br>        for(int i = 0;i&lt;gameboard.size;i++){<br>            if(gameboard.board[row][i] == null || gameboard.board[row][i].cellType != cellType){<br>                isrow = false;<br>            }<br>        }<br>        for(int i = 0;i&lt;gameboard.size;i++){<br>            if(gameboard.board[i][column] == null || gameboard.board[i][column].cellType != cellType){<br>                isColumn = false;<br>            }<br>        }<br>        for(int i = 0,j=0;i&lt;gameboard.size;i++,j++){<br>            if(gameboard.board[i][j] == null || gameboard.board[i][j].cellType != cellType){<br>                isDiagonal = false;<br>            }<br>        }<br>        for(int i = 0,j= gameboard.size-1;i&lt; gameboard.size;i++,j--){<br>            if(gameboard.board[i][j] == null || gameboard.board[i][j].cellType != cellType){<br>                isAntiDiagonal = false;<br>            }<br>        }<br>        return isrow || isColumn || isDiagonal || isAntiDiagonal;<br>    }<br><br><br><br>}</pre><p>The Game class is designed with several key components:</p><ul><li>Game class <strong>has-a </strong>Board and Player as part of its internal structure.</li><li>The startGame() function initiates the game.</li><li>The isWinner() function is responsible for determining the game&#39;s winner.</li><li>It employs a dequeue data structure to manage players, allowing for a turn-based rotation where players are removed from the front and added to the end of the dequeue, ensuring they get their turns.</li></ul><h3>Main Class</h3><pre>public class Main {<br>    public static void main(String[] args) {<br>        Game game = new Game();<br>        String result = game.startGame();<br>        if(result == &quot;Tie&quot;){<br>            System.out.println(&quot;Game is &quot; +  result);<br>        }else{<br>            System.out.println(&quot;Winner is &quot; + result);<br>        }<br><br>    }<br>}</pre><p>The main class serves as the entry point for starting the game and displaying the game result.</p><p>This completes our LLD of Tic Tac Toe .</p><p>Complete code Github link — <a href="https://github.com/manpreet1719/System-Design-LLD/tree/main/TicTacToe/src">https://github.com/manpreet1719/System-Design-LLD/tree/main/TicTacToe/src</a></p><p>Follow me on LinkedIn — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><p>However it is not a perfect solution. It still needs some improvements. Please provide your feedback .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=581ed4bb9281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between ngAfterViewInit and ngAfterContentInit with Example.]]></title>
            <link>https://medium.com/@manpreetkamboj6191/difference-between-ngafterviewinit-and-ngaftercontentinit-with-example-b15c48329258?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b15c48329258</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngafterviewinit]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ng]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 22:58:57 GMT</pubDate>
            <atom:updated>2023-09-22T23:00:12.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>Difference between ngAfterViewInit and ngAfterContentInit with example</h3><p><strong>What is ngAfterViewInit ?</strong></p><p>A lifecycle hook that is called after Angular has fully initialized a component’s view. Define an ngAfterViewInit() method to handle any additional initialization tasks.</p><p><strong>What is ngAfterContentInit ?</strong></p><p>A callback method that is invoked immediately after Angular has completed initialization of all of the directive’s content. It is invoked only once when the directive is instantiated.</p><p>This definition is from the documentation, but let’s break it down and understand it better with an example.</p><pre>//parent Component template file.<br><br>&lt;app-child&gt;<br>    &lt;div #ContentProjectionTemplate&gt;<br>        &lt;h1&gt;Content Projection&lt;/h1&gt;<br>    &lt;/div&gt;<br>&lt;/app-child&gt;</pre><p>We’ve made a parent component that includes a child component. We use a technique called “content projection” to insert the child component’s content into the parent component and assigning it the ID “ContentProjectionTemplate” for later access. We’ll explore this projected content in more detail as we proceed.</p><pre>//child Template file<br>&lt;div #Template&gt;<br>  &lt;h1&gt;Child Component&lt;/h1&gt;<br>&lt;/div&gt;<br>&lt;ng-content&gt;&lt;/ng-content&gt;<br><br></pre><p>We’ve created a &lt;div&gt; element with the ID &quot;Template&quot; for easy access. Inside this element, we&#39;ve included &lt;ng-content&gt;&lt;/ng-content&gt; to inform the child component that there is “ContentProjectionTemplate”<strong> </strong>code projected within the parent component.</p><pre>import { Component, ContentChild, ElementRef, OnInit, ViewChild } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  templateUrl: &#39;./child.component.html&#39;,<br>  styleUrls: [&#39;./child.component.css&#39;]<br>})<br>export class ChildComponent implements OnInit {<br><br>  @ViewChild(&#39;Template&#39;,{static : false}) Template : ElementRef<br><br>  @ContentChild(&#39;ContentProjectionTemplate&#39;,{static : false}) ContentProjectionTemplate : ElementRef;<br><br><br>  constructor() { }<br><br>  ngOnInit() {<br>  }<br>  ngAfterViewInit(){<br>    console.log(&quot;ngAfterViewInit&quot;)<br>    console.log(this.Template); // Refer to -&gt; Element Ref -&gt; some object<br>    console.log(this.ContentProjectionTemplate); // Refer to -&gt; Element Ref -&gt; some object<br>  }<br>  ngAfterContentInit() {<br>    console.log(&quot;ngAfterContentInit&quot;)<br>    console.log(this.Template); // Refer to -&gt; undefined<br>    console.log(this.ContentProjectionTemplate);// Refer to -&gt; Element Ref -&gt; some object<br>  }<br><br>}</pre><p>In this code, we’re doing two things:</p><ol><li>We’re using @ViewChild to grab a &lt;div&gt; element in the child component using the ID “Template”</li><li>We’re also using @ContentChild to access content that&#39;s been projected into the child component from the parent component, which is identified by the ID “ContentProjectionTemplate”</li></ol><p>Now let us check the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Fs4f3KCkG82HwcyNsi66Hg.png" /></figure><p>1 . When we console log the values of “Template” and “ContentProjectionTemplate ”in the ngAfterViewInit lifecycle hook, both refer to some object.</p><p>2 . When we attempt to log the values of “Template”<strong> </strong>and “ContentProjectionTemplate” within the ngAfterContentInit lifecycle hook, we will observe that the “Template”<strong> </strong>variable is <strong>undefined</strong>, while “ContentProjectionTemplate” will refer to some object.</p><p>Here we can Clearly see the Difference</p><p>In ngAfterContentInit, the “Template” is still undefined because only the content projection within the component has been initialized. However, in ngAfterViewInit, the entire view&#39;s DOM (Document Object Model) has finished initializing, including the “Template” and all its elements.</p><p>I hope you liked it follow me on linkedin — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b15c48329258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between Package.json and Package-lock.json files]]></title>
            <link>https://medium.com/@manpreetkamboj6191/difference-between-package-json-and-package-lock-json-files-15696aeedb3b?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/15696aeedb3b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 12:37:35 GMT</pubDate>
            <atom:updated>2023-09-12T12:37:35.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epkJIQo5cjrxEveCbSU2QA.png" /></figure><h3>What is package.json?</h3><p>The <strong>package.json</strong> is the principal place to configure and define how to interact with and manage your application. For example, the <a href="https://docs.npmjs.com/cli/v7">npm CLI</a> uses this file to start your project, install dependencies, run scripts, etc.</p><p>In the world of Node.js development, package.json and package-lock.json play important roles in managing project dependencies and ensuring consistency across different developers environments. When npm install command is run then NPM will generate the node_modules folder and package-lock.json file. You might wonder why package-lock.json is generated if you already have a package.json file.</p><h3>What is need of package-lock.json?</h3><p>However, the package-lock.json solve crucial issue maintaining version consistency.</p><p>Consider this scenario —</p><p><strong>Developer 1 </strong>works on a project and <strong>Developer 2 </strong>joins the team later to implement a new feature. Without a package-lock.json file, running ‘npm install’ could result in the installation of different dependency versions. This is where package-lock.json shines it locks the required dependencies and versions, ensuring that all team members are on the same page. By committing the package-lock.json file, you establish a shared reference point. When another developer clones the project and runs npm install, they’ll get the exact packages and versions specified in the package-lock.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPhpzOuQeK_-ccrASaEYfg.png" /></figure><h3><strong>What is tilde (~) and Caret (^) ?</strong></h3><p>In your package.json file, you’ll often encounter two symbols: the tilde (~) and the caret (^). These symbols are essential for defining version ranges:</p><p>The tilde (~) signifies a safe update strategy. For instance, if you see ‘~1.0.8,’ version it means npm will install version 1.0.8 or any later patch version like 1.0.9. This keeps you within the same <strong>minor version.</strong></p><p>The caret (^) represents a compatible update strategy. If you encounter 1.0.3 version npm will install version 1.0.3 or the latest minor or patch version, like 1.1.0, while still staying within the same major version.</p><p>In summary, package.json and package-lock.json are important tools for Node.js developers, ensuring project consistency and facilitating collaborative development by locking dependencies and defining version ranges with precision.</p><p>Follow — <a href="https://www.linkedin.com/in/manpreet-kamboj-37178716b/">https://www.linkedin.com/in/manpreet-kamboj-37178716b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15696aeedb3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Code Outside NgZone in Angular for Improved Performance]]></title>
            <link>https://medium.com/@manpreetkamboj6191/running-code-outside-ngzone-in-angular-for-improved-performance-35e586bb9421?source=rss-818177f3e9f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e586bb9421</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[change-detection]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Manpreetkamboj]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 09:16:57 GMT</pubDate>
            <atom:updated>2023-09-08T09:16:57.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular’s change detection mechanism, powered by NgZone, is at the heart of the framework’s real-time data synchronization and seamless user experience. NgZone is responsible for notifying Angular when to perform the change detection process, which can sometimes be a performance bottleneck in certain scenarios. To overcome this limitation and boost the performance of your Angular application, there are times when you need to execute code outside of the NgZone.</p><h3>Why Run Code Outside NgZone?</h3><p>Before diving into how to run code outside of NgZone, it’s essential to understand why you might want to do so. Angular default behaviour is to trigger change detection on every user interaction, timer event, or asynchronous operation. While this ensures that your application remains responsive, it can also lead to unnecessary and frequent change detection cycles, which impact performance.</p><p>Running specific code outside NgZone can be beneficial in the following situations:</p><ol><li>Performance Optimization: Running code outside of NgZone can significantly improve your application’s performance by reducing the frequency of change detection cycles.</li><li>Avoiding Unnecessary Change Detection: Some operations, like third-party library callbacks or WebSocket events, don’t require Angular to check for changes. Running these operations outside NgZone can prevent Angular from needlessly evaluating your component templates.</li><li>Preventing Expression Evaluation: In cases where you want to prevent Angular from evaluating expressions in templates, running code outside NgZone can help.</li></ol><h3>How to Run Code Outside NgZone?</h3><p>To run code outside NgZone, Angular provides a utility function called runOutsideAngular. This function allows you to execute a specific piece of code outside the Angular change detection zone. Here&#39;s how to use it:</p><pre>import { Component, NgZone } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-component&#39;,<br>  template: `<br>    &lt;!-- Your component template --&gt;<br>  `,<br>})<br>export class MyComponent {<br>  constructor(private ngZone: NgZone) {}<br><br>  ngOnInit() {<br>    // Run code outside NgZone<br>    this.ngZone.runOutsideAngular(() =&gt; {<br>      // Place your code here<br>      // This code will not trigger change detection<br>    });<br>  }<br>}</pre><p>In the above example, we import the NgZone service and use its runOutsideAngular method to execute code outside the Angular zone. Any code placed within this function won&#39;t trigger change detection, providing a performance boost for the specified operations.</p><p>Here’s an example of running an event inside and outside the NgZone in an Angular component:</p><pre>// Run Inside NgZone<br>&lt;button (click)=&quot;runInsideZone()&quot;&gt;Run Inside NgZone&lt;/button&gt; <br><br>//Run Outside NgZone<br>&lt;button #Zoneless&gt;Run Outside NgZone&lt;/button&gt;<br><br>&lt;p&gt;Counter (Inside NgZone): {{ counterInside }}&lt;/p&gt;<br>&lt;p&gt;Counter (Outside NgZone): {{ counterOutside }}&lt;/p&gt;</pre><pre>import { Component, ElementRef, NgZone, ViewChild } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent {<br>  counterInside = 0;<br>  counterOutside = 0;<br><br>  @ViewChild(&#39;Zoneless&#39;,{static : true,read: ElementRef}) buttonelement;<br><br>  constructor(private ngZone: NgZone) {}<br><br><br><br>  ngOnInit(){<br>    this.ngZone.runOutsideAngular(() =&gt; {<br>      this.buttonelement.nativeElement.addEventListener(&quot;click&quot;, () =&gt; {<br>        console.log(&quot;onClick&quot;);<br>        this.counterOutside++;<br>      });<br>    });<br>  }<br><br>  runInsideZone() {<br>    // This event handler runs inside the NgZone.<br>    this.ngZone.run(() =&gt; {<br>      this.counterInside++;<br>    });<br>  }<br>}</pre><p>In this example, there are two buttons: “Run Inside NgZone” and “Run Outside NgZone.” When you click the “Run Inside NgZone” button, its associated event handler runs inside the NgZone, automatically triggering Angular’s change detection. This results in an increase in the counterInside value, which is reflected in the view. However, when you click the &quot;Run Outside NgZone&quot; button, its event handler runs outside the NgZone. As a result, the counterOutside count does not increase immediately, and you need to manually trigger Angular&#39;s change detection for the view to update with the new count. This example illustrates the difference in behavior between running code inside and outside of the NgZone in an Angular application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e586bb9421" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>