<?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 Sreekumar P on Medium]]></title>
        <description><![CDATA[Stories by Sreekumar P on Medium]]></description>
        <link>https://medium.com/@sreekumarp?source=rss-dfcdcb5cf2e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xo5ssiXmdcqy0kEDu_jtxA.jpeg</url>
            <title>Stories by Sreekumar P on Medium</title>
            <link>https://medium.com/@sreekumarp?source=rss-dfcdcb5cf2e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:28:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sreekumarp/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[CSS Gets Conditional! Introducing the if() Function for Smarter Styles]]></title>
            <link>https://sreekumarp.medium.com/css-gets-conditional-introducing-the-if-function-for-smarter-styles-f976cc0d6ede?source=rss-dfcdcb5cf2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f976cc0d6ede</guid>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[Sreekumar P]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 07:11:10 GMT</pubDate>
            <atom:updated>2025-06-03T13:17:14.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B9XknEMcDTmnGfYd" /></figure><p>For years, developers have wished for more robust conditional logic directly within CSS. While :hover, :focus, media queries, and more recently, container queries have given us powerful contextual styling, true if/else behavior for arbitrary property values has often meant reaching for JavaScript.</p><p>But the CSS landscape is always evolving! Enter the new <strong>CSS </strong><strong>if() function</strong>, a powerful addition landing in <strong>Chrome 137</strong> (and other browsers as specs solidify and implementations follow). This function, part of the CSS Conditional Rules Level 5 specification, allows you to choose between two values based on a condition, opening up exciting possibilities for declarative, stateful styling.</p><p>Let’s dive into how it works, using an example similar to creating stateful UI components like task cards.</p><h3>What is the CSS if() function?</h3><p>At its core, the if() function lets you apply one of two values to a CSS property based on a conditional check. The basic syntax looks like this:</p><pre>property: if( &lt;condition&gt;, &lt;value_if_true&gt;, &lt;value_if_false_or_else_if&gt; );</pre><ul><li>&lt;condition&gt;: This is typically a <strong>style query</strong>. Style queries allow you to check the computed value of a custom property. For example, style(--theme: dark) would be true if the custom property --theme is set to dark.</li><li>&lt;value_if_true&gt;: The value to apply if the condition evaluates to true.</li><li>&lt;value_if_false_or_else_if&gt;: The value to apply if the condition is false. Importantly, this &quot;else&quot; part can also be <em>another </em><em>if() function</em>, allowing you to chain conditions (like an else if structure).</li></ul><h3>The Magic: Connecting if() to Your Data with attr()</h3><p>One of the most powerful ways to leverage if() is by combining it with custom properties that are dynamically set from HTML data attributes. This is where CSS can start reacting to the semantic state of your elements.</p><p>The attr() function in CSS has been around, but its capabilities have been extended. We can now use it to pull the value of an HTML attribute and assign it to a custom property, even specifying its type. For string-like identifiers (like &quot;pending&quot;, &quot;complete&quot;), we use &lt;custom-ident&gt;:</p><pre>.card {<br>  /* Reads the &#39;data-status&#39; attribute */<br>  --status: attr(data-status type &lt;custom-ident&gt;); <br>}</pre><p>If you have HTML like this:</p><pre>&lt;div class=&quot;card&quot; data-status=&quot;pending&quot;&gt;<br>  Build demo to showcase if() function in CSS<br>&lt;/div&gt;<br>&lt;div class=&quot;card&quot; data-status=&quot;complete&quot;&gt;<br>  Create a div with a data-status on it<br>&lt;/div&gt;<br>&lt;div class=&quot;card&quot; data-status=&quot;inactive&quot;&gt;<br>  Give Una a high-five<br>&lt;/div&gt;</pre><p>Then, for the first card, --status will effectively be pending. For the second, it will be complete, and so on. This --status custom property is now what our if() function can query!</p><h3>Building Stateful Cards: A Practical Example</h3><p>Let’s style our cards based on their data-status.</p><p><strong>HTML:</strong></p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;card&quot; data-status=&quot;pending&quot;&gt;<br>    &lt;div class=&quot;title&quot;&gt;Build demo to showcase if() function in CSS&lt;/div&gt;<br>    &lt;figure class=&quot;user&quot;&gt;&lt;img src=&quot;una.jpg&quot; alt=&quot;Una&quot;&gt;&lt;/figure&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;card&quot; data-status=&quot;complete&quot;&gt;<br>    &lt;div class=&quot;title&quot;&gt;Create a div with a data-status on it&lt;/div&gt;<br>    &lt;figure class=&quot;user&quot;&gt;&lt;img src=&quot;una.jpg&quot; alt=&quot;Una&quot;&gt;&lt;/figure&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;card&quot; data-status=&quot;inactive&quot;&gt;<br>    &lt;div class=&quot;title&quot;&gt;Give Una a high-five&lt;/div&gt;<br>    &lt;figure class=&quot;user&quot;&gt;&lt;img src=&quot;bramus.jpg&quot; alt=&quot;Bramus&quot;&gt;&lt;/figure&gt;<br>  &lt;/div&gt;<br>  &lt;!-- ... more cards ... --&gt;<br>&lt;/div&gt;</pre><p><strong>CSS:</strong></p><pre>/* 1. Define the custom property from the data attribute */<br>.card {<br>  --status: attr(data-status type &lt;custom-ident&gt;); /* Crucial for if() */<br>  /* Basic card styling */<br>  padding: 1rem;<br>  border: 2px solid gray; /* Default border */<br>  border-radius: 0.5rem;<br>  background-color: #f9f9f9; /* Default background */<br>  margin-bottom: 1rem;<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>}<br><br>.title {<br>  margin-right: 1rem;<br>}<br><br>.user img {<br>  width: 40px;<br>  height: 40px;<br>  border-radius: 50%;<br>  object-fit: cover;<br>}<br><br>/* 2. Use if() to apply conditional styles */<br>.card {<br>  border-color: if(<br>    style(--status: pending), royalblue, /* if status is pending */<br>    if(<br>      style(--status: complete), seagreen, /* else if status is complete */<br>      gray /* else (for inactive or any other status) */<br>    )<br>  );<br><br>  background-color: if(<br>    style(--status: pending), #e6f0ff, /* Light blue for pending */<br>    if(<br>      style(--status: complete), #e6fff2, /* Light green for complete */<br>      #efefef /* Light gray for inactive/default */<br>    )<br>  );<br>}<br><br>/* Example: Using if() for layout changes with CSS Grid */<br>.container {<br>  display: grid;<br>  grid-template-columns: repeat(3, 1fr); /* 3-column layout */<br>  gap: 1rem;<br>  max-width: 900px;<br>  margin: 2rem auto;<br><br>  /* Accessibility: Ensure reading order matches visual grid flow */<br>  reading-flow: grid-columns;<br>}<br><br>.card {<br>  /* Change grid column based on status */<br>  grid-column: if(<br>    style(--status: pending), 1, /* Pending tasks in the first column */<br>    if(<br>      style(--status: complete), 2,/* Complete tasks in the second column*/<br>      3 /* Inactive/other tasks in the third column */<br>    )<br>  );<br>}</pre><ul><li><strong>--status: attr(data-status type &lt;custom-ident&gt;);</strong>: On each .card, we create a local custom property --status and populate it with the value of its data-status attribute.</li><li><strong>border-color</strong>:</li></ul><blockquote>if(style(--status: pending), royalblue, ...): Checks if --status is pending. If true, border-color is royalblue.</blockquote><blockquote>If false, it moves to the “else” part, which is another if(): if(style(--status: complete), seagreen, gray).</blockquote><blockquote>This inner if() checks if --status is complete. If true, border-color is seagreen.</blockquote><blockquote>If false (meaning it’s neither pending nor complete), border-color defaults to gray.</blockquote><ul><li><strong>background-color</strong>: Follows the same nested if() logic for different background shades.</li><li><strong>grid-column</strong>: This demonstrates using if() for more structural styling. Cards are placed into different grid columns based on their status.</li></ul><h3><strong>Accessibility Note: </strong><strong>reading-flow</strong></h3><p>When you visually reorder elements using CSS Grid or Flexbox (as we did with grid-column above), it&#39;s crucial to ensure that the reading order for assistive technologies (like screen readers) matches the visual flow.</p><p>When you visually reorder elements using CSS Grid or Flexbox (as we did with grid-column above), it&#39;s crucial to ensure that the reading order for assistive technologies (like screen readers) matches the visual flow.</p><p>The new reading-flow property (also landing in Chrome 137) helps with this. By setting reading-flow: grid-columns; on the .container, we instruct the browser that the logical reading sequence should follow the columns of the grid, aligning the experience for sighted and non-sighted users. You can learn more about reading-flow and reading-order on <a href="https://developer.chrome.com/blog/reading-flow-order">developer.chrome.com</a>.</p><h3>Why is CSS if() Exciting?</h3><ul><li><strong>Declarative Logic:</strong> Express conditions directly in your stylesheet.</li><li><strong>Reduced JavaScript:</strong> For presentational logic that depends on an element’s state (exposed via data attributes), you might not need JS to toggle classes anymore.</li><li><strong>More Stateful Components:</strong> Create components that adapt their appearance based on their data, purely with CSS.</li><li><strong>Clean Markup:</strong> Keep your HTML semantic and let CSS handle the conditional presentation.</li><li><strong>Composability:</strong> Works beautifully with CSS custom properties.</li></ul><h3>Browser Support and The Future</h3><p>As of writing, CSS if() and typed attr() are newest additions, starting to land in <strong>Chrome 137</strong>. Support in other browsers will hopefully follow as the specification matures. Always check <a href="https://caniuse.com/">Can I Use</a> for the latest browser compatibility for if() and attr() (especially the typed version).</p><p>This is a fantastic step forward for CSS, giving us more tools to build sophisticated and responsive UIs with less reliance on other languages for presentational concerns.</p><p>What cool use cases can you think of for CSS if()? Let us know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f976cc0d6ede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cancel HTTP requests in Angular — HTTP Service wrapper]]></title>
            <link>https://sreekumarp.medium.com/cancel-http-requests-in-angular-http-service-wrapper-2cedcf2269ad?source=rss-dfcdcb5cf2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cedcf2269ad</guid>
            <category><![CDATA[cancel]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Sreekumar P]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 12:37:57 GMT</pubDate>
            <atom:updated>2025-06-03T11:15:59.072Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cancel HTTP requests in Angular — HTTP Service wrapper</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*n7iSlrG5VyB0VTxHcEQQQQ.png" /></figure><p>When building modern web applications, managing HTTP requests efficiently is crucial for maintaining performance and user experience. One common challenge is handling duplicate or redundant HTTP requests, which can lead to unnecessary network traffic and potential data inconsistencies. In this blog post, we’ll explore how to cancel ongoing HTTP requests in Angular using a method from a custom HttpService class: cancelPreviousRequestIfAny.</p><h3>Why Cancel HTTP Requests?</h3><p>Imagine a scenario where a user is typing in a search box, and each keystroke triggers an HTTP request to fetch search results. Without canceling the previous request, multiple requests may overlap, leading to:</p><ul><li><strong>Unnecessary network usage</strong>: Multiple requests for outdated data are sent.</li><li><strong>Race conditions</strong>: Responses may arrive out of order, causing incorrect data to be displayed.</li></ul><p>To address this, we can cancel the previous request before initiating a new one.</p><h3>The cancelPreviousRequestIfAny Method</h3><p>The cancelPreviousRequestIfAny method in the HttpService class is designed to handle this scenario. It ensures that any ongoing HTTP request associated with a specific caller or cache key is canceled before starting a new one.</p><p>Here’s the implementation:</p><pre>/**<br> * Cancels any previous request associated with the given caller and cache key.<br> * @param caller - Unique identifier for the caller of the request.<br> * @param cacheKey - Optional cache key for managing inflight requests.<br> * @returns A new subject used to cancel the current request.<br> */<br>private cancelPreviousRequestIfAny(caller: Caller, cacheKey?: string): Subject&lt;void&gt; {<br>  const requestCancelRef = new Subject&lt;void&gt;();<br>  if (caller) {<br>    this.closeExistingTrackerSubject(caller);<br>    this.requestTrackerList[caller] = { tracker: requestCancelRef, cacheKey };<br>  }<br>  return requestCancelRef;<br>}</pre><h3>How It Works</h3><ol><li><strong>Create a New Cancellation Subject</strong>:</li></ol><p>A Subject&lt;void&gt; is created to act as a cancellation signal for the new request.</p><p><strong>2. Close Existing Tracker</strong>:</p><p>The method calls closeExistingTrackerSubject(caller) to cancel and clean up any ongoing request associated with the given caller.</p><p><strong>3. Update the Tracker List</strong>:</p><p>The requestTrackerList dictionary is updated to associate the new cancellation subject with the caller and optional cacheKey.</p><p><strong>4. Return the Cancellation Subject</strong>:</p><p>The new Subject&lt;void&gt; is returned, which can be used to cancel the new request when needed.</p><h3>Supporting Method: closeExistingTrackerSubject</h3><p>The closeExistingTrackerSubject method is responsible for canceling and cleaning up any existing request tracker:</p><pre>/**<br> * Closes any existing tracker subject associated with the given caller.<br> * @param caller - Unique identifier for the caller of the request.<br> * @param close - Whether to close the tracker subject (default is true).<br> * @returns A boolean indicating whether an existing tracker was closed.<br> */<br>private closeExistingTrackerSubject(caller: Caller, close = true): boolean {<br>  if (!caller) return false;<br>  <br>  const existingCall = this.requestTrackerList[caller];<br>  if (existingCall?.tracker) {<br>    if (close) {<br>      existingCall.tracker.next();<br>      existingCall.tracker.complete();<br>      if (existingCall.cacheKey) {<br>        this.cacheService.clearInflightRequest(existingCall.cacheKey);<br>      }<br>    }<br>    delete this.requestTrackerList[caller];<br>    return true;<br>  }<br>  return false;<br>}</pre><p>This method ensures that any ongoing request is properly canceled and removed from the requestTrackerList.</p><h3>Example Usage</h3><p>Here’s how the cancelPreviousRequestIfAny method integrates into the HttpService class:</p><pre>private requestWrapper&lt;T&gt;(<br>  source: Observable&lt;T&gt;,<br>  caller: Caller,<br>  cacheKey?: string,<br>  suppressErrorCodes?: number[]<br>): Observable&lt;T&gt; {<br>  const requestCancelRef = this.cancelPreviousRequestIfAny(caller, cacheKey);<br>  return source.pipe(<br>    catchError(this.handleError&lt;T&gt;(suppressErrorCodes)),<br>    tap(() =&gt; this.closeExistingTrackerSubject(caller, false)),<br>    takeUntil(this.getTracker(requestCancelRef))<br>  );<br>}</pre><p>In this example, the requestWrapper method uses cancelPreviousRequestIfAny to ensure that any previous request is canceled before subscribing to the new observable.</p><h3>Benefits of This Approach</h3><ul><li><strong>Efficient Resource Management</strong>: Prevents redundant network requests, saving bandwidth and server resources.</li><li><strong>Improved User Experience</strong>: Ensures that only the latest data is displayed to the user.</li><li><strong>Simplified Code</strong>: Centralizes request cancellation logic, making it easier to maintain and reuse.</li></ul><h3>Source code for wrapper HTTP Service</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a56ef56b83c52f5f4c5b77d0948fdd/href">https://medium.com/media/28a56ef56b83c52f5f4c5b77d0948fdd/href</a></iframe><h3>Conclusion</h3><p>The cancelPreviousRequestIfAny method is a powerful tool for managing HTTP requests in Angular applications. By canceling redundant requests, it helps improve performance and ensures data consistency. If you&#39;re building an Angular app with complex HTTP interactions, consider implementing a similar approach to streamline your request handling.</p><p>happy coding… :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cedcf2269ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Signals vs. React: A Deep Dive into Reactivity]]></title>
            <link>https://sreekumarp.medium.com/angular-signals-vs-react-a-deep-dive-into-reactivity-3c6835f92945?source=rss-dfcdcb5cf2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6835f92945</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[reactivity]]></category>
            <dc:creator><![CDATA[Sreekumar P]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 07:05:42 GMT</pubDate>
            <atom:updated>2025-03-21T07:05:42.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkeulZeZbsy5v7bom6Warg.png" /></figure><p>State management and reactivity are fundamental to modern front-end frameworks. With <strong>Angular 17</strong> introducing <strong>Signals</strong>, developers now have a <strong>fine-grained reactivity model</strong> similar to concepts in React. But how do <strong>Angular Signals</strong> compare with <strong>React Hooks</strong> like useState, useEffect, and useMemo? Let’s break it down.</p><h3>🔹 What Are Angular Signals?</h3><p>Angular Signals provide <strong>reactive state tracking</strong> by letting developers define <strong>mutable, reactive variables</strong> that trigger updates when changed.</p><h3>Example: Using Signals in Angular</h3><pre>import { signal } from &#39;@angular/core&#39;;</pre><pre>export class CounterComponent {<br>  count = signal(0);<br>  increment() {<br>    this.count.set(this.count() + 1);<br>  }<br>}</pre><p>✅ No need for ChangeDetectorRef<br>✅ Eliminates unnecessary re-renders</p><h3>🔹 How Angular Signals Compare with React Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*qj3GKOElkH1DDHC1cldzdA.png" /></figure><h3>1️⃣ Signals vs. useState (Managing State)</h3><h3>🔹 React useState</h3><pre>import { useState } from &quot;react&quot;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>  return &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;;<br>}</pre><ul><li><strong>Triggers a re-render of the component</strong></li><li><strong>Uses Virtual DOM diffing to update the UI</strong></li></ul><h3>🔹 Angular Signals (More Efficient State Tracking)</h3><pre>import { signal } from &#39;@angular/core&#39;;</pre><pre>export class CounterComponent {<br>  count = signal(0);<br>  increment() {<br>    this.count.set(this.count() + 1);<br>  }<br>}</pre><p>✅ <strong>Does NOT re-render the entire component</strong><br>✅ <strong>Directly updates only dependent parts</strong></p><p>📌 <strong>Verdict:</strong> <strong>Angular Signals are more efficient</strong> because they track <strong>exact dependencies</strong> instead of triggering full re-renders.</p><h3>2️⃣ Computed Signals vs. useMemo (Derived State)</h3><h3>🔹 React useMemo</h3><pre>const doubled = useMemo(() =&gt; count * 2, [count]);</pre><ul><li>Runs only when count changes</li><li>Avoids unnecessary calculations</li></ul><h3>🔹 Angular computed Signal</h3><pre>const doubled = computed(() =&gt; count() * 2);</pre><p>✅ <strong>Does not need a dependency array</strong><br> ✅ <strong>Automatically tracks dependencies</strong></p><p>📌 <strong>Verdict:</strong> <strong>Angular </strong><strong>computed is more intuitive</strong>, as it avoids React’s dependency array pitfalls.</p><h3>3️⃣ Signals effect() vs. useEffect() (Handling Side Effects)</h3><p>Both React’s useEffect and Angular&#39;s Signals with effects serve as mechanisms to handle side effects in response to changes in state or data. However, they operate within their respective frameworks (React and Angular) and have different implementations and use cases. Here&#39;s a comparison of the two:</p><h3>React useEffect</h3><ul><li><strong>Purpose</strong>: useEffect is a React Hook that allows you to perform side effects in functional components. It runs after the component renders and can respond to changes in state or props.</li></ul><p><strong>Key Features</strong>:</p><ul><li>Runs after every render by default (unless dependencies are specified).</li><li>Can be used to fetch data, subscribe to events, or manually manipulate the DOM.</li><li>Supports cleanup via a return function (e.g., unsubscribing from events or clearing timers).</li><li>Dependency array controls when the effect runs:</li><li>Empty array ([]): Runs only once after the initial render.</li><li>Specific dependencies: Runs when those dependencies change.</li></ul><p><strong>Example</strong>:</p><pre>useEffect(() =&gt; {<br>  console.log(&#39;Component rendered or state changed&#39;);<br>  return () =&gt; {<br>    console.log(&#39;Cleanup before re-running effect or unmounting&#39;);<br>  };<br>}, [someState]);</pre><h3>Angular Signals Effect</h3><ul><li><strong>Purpose</strong>: Angular Signals (introduced in Angular 16) provide a reactive way to manage state. Effects in Angular Signals allow you to react to changes in signal values and perform side effects.</li></ul><p><strong>Key Features</strong>:</p><ul><li>Automatically tracks dependencies (signals used inside the effect).</li><li>Runs whenever any of the tracked signals change.</li><li>Supports cleanup via a return function.</li><li>Designed to work seamlessly with Angular’s change detection and reactivity system.</li></ul><p><strong>Example</strong>:</p><pre>const count = signal(0);<br><br>effect(() =&gt; {<br>  console.log(&#39;Count changed:&#39;, count());<br>  return () =&gt; {<br>    console.log(&#39;Cleanup before re-running effect&#39;);<br>  };<br>});</pre><h3>When to Use Which</h3><p><strong>React </strong><strong>useEffect</strong>:</p><ul><li>Use when working with React functional components.</li><li>Ideal for side effects tied to component lifecycle (mount, update, unmount).</li><li>Suitable for integrating with non-reactive libraries or APIs.</li></ul><h3><strong>Angular Signals Effect</strong>:</h3><ul><li>Use when working with Angular and its reactive state management (Signals).</li><li>Ideal for reacting to changes in signal values.</li><li>Fits well with Angular’s change detection and reactivity model.</li></ul><h3>📌 <strong>Verdict:</strong></h3><ul><li>React’s useEffect is a lifecycle-based side-effect handler, while Angular Signals effects are reactive and tied to signal changes.</li><li>Both support cleanup and dependency tracking, but Angular Signals effects automate dependency tracking, whereas React requires explicit dependency arrays.</li><li>The choice depends on the framework you’re using and the specific use case for handling side effects.</li></ul><h3>🔹 When Should You Use Angular Signals vs. React Hooks?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*IR5hFLAXFilbXPAghdPItA.png" /></figure><h3>📌 Conclusion: Which Is Better?</h3><p>✅ <strong>Angular Signals</strong> provide <strong>automatic dependency tracking, fine-grained updates, and improved performance</strong> without unnecessary re-renders.<br>✅ <strong>React Hooks</strong> rely on <strong>Virtual DOM diffing</strong> and require dependency arrays, making them <strong>less intuitive</strong> for state tracking.</p><p><strong>Choose React Hooks if</strong>:</p><ul><li>You’re working in a React environment.</li><li>You prefer a lightweight, flexible, and extensible approach to state and side effects.</li><li>You need access to a vast ecosystem of third-party libraries.</li><li>You’re comfortable managing dependencies and optimizing performance manually.</li></ul><p><strong>Choose Angular Signals if</strong>:</p><ul><li>You’re working in an Angular environment.</li><li>You want a built-in, reactive state management solution that integrates seamlessly with Angular’s change detection.</li><li>You prefer automatic dependency tracking and fine-grained reactivity.</li><li>You’re building complex applications where performance and scalability are critical.</li></ul><p>🚀 <strong>Angular is evolving</strong> toward a <strong>reactivity model closer to Solid.js and Svelte</strong>, making Signals a game-changer for Angular developers.</p><p>#Angular #React #WebDevelopment #StateManagement #Performance #Frontend</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6835f92945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Advanced Angular Signals ]]></title>
            <link>https://sreekumarp.medium.com/mastering-advanced-angular-signals-b2aebb3ecd33?source=rss-dfcdcb5cf2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2aebb3ecd33</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Sreekumar P]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 09:15:00 GMT</pubDate>
            <atom:updated>2025-02-02T09:15:00.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*HpTZUEd_o0tHy2NZoHCBEg.png" /></figure><p>Angular Signals provide <strong>fine-grained reactivity</strong>, helping developers build efficient and scalable applications. But beyond the basics, <strong>how can we leverage their full potential?</strong></p><h3>Understanding Angular Signals 🚀</h3><p>Angular Signals are a <strong>reactive state management</strong> feature that helps track and manage application state efficiently. They bring fine-grained <strong>reactivity</strong> to Angular applications, improving performance and simplifying state updates.</p><h3>Why Use Signals in Angular?</h3><p>✅ <strong>Automatic Change Detection</strong> — Signals track dependencies automatically, reducing unnecessary re-renders.<br> ✅ <strong>Fine-Grained Reactivity</strong> — Unlike RxJS, signals update only the necessary components.<br> ✅ <strong>Simplified State Management</strong> — No need for complex observables; use <strong>signals</strong> to store and update state.<br> ✅ <strong>Improved Performance</strong> — Eliminates extra computations and re-renders, making Angular apps faster.</p><h3>Key Concepts of Signals</h3><h4>🔹 <strong>Creating a Signal</strong></h4><pre>import { signal } from &#39;@angular/core&#39;;<br><br>const counter = signal(0);</pre><h4>🔹 <strong>Updating a Signal</strong></h4><pre>console.log(counter()); // 0</pre><h4>🔹 Updating a Signal</h4><pre>counter.set(10);  // Directly set a new value<br>counter.update(value =&gt; value + 1);  // Increment</pre><p>🔹 <strong>Computed Signals (Derived State)</strong></p><pre>const doubleCounter = computed(() =&gt; counter() * 2);</pre><p>🔹 <strong>Effects (React to Changes)</strong></p><pre>effect(() =&gt; {<br>  console.log(&#39;Counter changed:&#39;, counter());<br>});</pre><h3>Deep Dive Into Advanced Angular Signals</h3><h3>1️⃣ Computed Signals — Derived State Without Re-Rendering</h3><p>Computed signals let you derive <strong>reactive values</strong> based on other signals.</p><pre>import { signal, computed } from &#39;@angular/core&#39;;</pre><pre>import { signal, computed } from &#39;@angular/core&#39;;<br><br><br>const basePrice = signal(100);<br>const tax = signal(0.2);<br>// Computed signal: Auto-updates when dependencies change<br>const finalPrice = computed(() =&gt; basePrice() * (1 + tax()));</pre><p>💡 <strong>Benefit</strong>: Computed signals only recalculate <strong>when their dependencies change</strong>, reducing unnecessary computations.</p><h3>2️⃣ Effects — Reacting to Signal Changes</h3><p>Effects run <strong>automatically</strong> when a signal inside them changes. Think of them like RxJS tap() but for signals.</p><pre>import { signal, effect } from &#39;@angular/core&#39;;</pre><pre>const username = signal(&#39;Jude&#39;);<br><br>effect(() =&gt; {<br>  console.log(`User changed: ${username()}`);<br>});<br><br>// Updating the signal triggers the effect<br>username.set(&#39;Alex&#39;); // Logs: &quot;User changed: Alex&quot;</pre><p>💡 <strong>Best Use Case</strong>: Logging, API calls, or DOM updates <strong>without</strong> manual subscriptions.</p><h3>3️⃣ Signal-Based Components — No More Zone.js?</h3><p><strong>Signals</strong> enable <strong>zone-less change detection</strong>, improving <strong>performance</strong> 🚀.<br> Here’s how to use signals in a <strong>signal-based component</strong> (Angular 17+):</p><pre>import { Component, signal } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `&lt;button (click)=&quot;increment()&quot;&gt;Count: {{ count() }}&lt;/button&gt;`,<br>})<br>export class CounterComponent {<br>  count = signal(0);<br>  increment() {<br>    this.count.update(value =&gt; value + 1);<br>  }<br>}</pre><p>💡 <strong>Why is this revolutionary?</strong><br> ✅ No need for ChangeDetectorRef.detectChanges()<br> ✅ Avoids unnecessary re-renders</p><h3>4️⃣ Immutability With Signals</h3><p>By default, signals enforce <strong>immutability</strong>, meaning objects inside signals should be <strong>replaced, not mutated</strong>.<br> ❌ <strong>Bad (Mutating the Object)</strong></p><pre>const user = signal({ name: &#39;Alice&#39;, age: 25 });<br>user().age = 26; // ❌ Won&#39;t trigger updates!</pre><p>✅ <strong>Good (Replacing the Object)</strong></p><pre>user.set({ ...user(), age: 26 });</pre><p>💡 <strong>Why?</strong> Angular signals track references, not internal mutations.</p><h3>5️⃣ Using Signals With RxJS</h3><p>Since Angular heavily uses <strong>RxJS</strong>, how do we <strong>bridge the gap</strong> between Signals and Observables?</p><p>✅ <strong>Convert an Observable to a Signal</strong></p><pre>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>constructor(private http: HttpClient) {}<br>userData = toSignal(this.http.get(&#39;/api/user&#39;));</pre><p>✅ <strong>Convert a Signal to an Observable</strong></p><pre>import { toObservable } from &#39;@angular/core/rxjs-interop&#39;;</pre><pre>const countSignal = signal(0);<br>const count$ = toObservable(countSignal);</pre><p>💡 <strong>Why?</strong> This helps <strong>integrate signals into existing RxJS-based Angular apps</strong>.</p><h3>🛠 When Should You Use Signals?</h3><p>✔️ <strong>Component Local State</strong> (e.g., form inputs, UI state)<br> ✔️ <strong>Performance Optimization</strong> (No ChangeDetectorRef needed)<br> ✔️ <strong>Computed Values</strong> (Avoiding unnecessary calculations)<br> ✔️ <strong>Event-Driven Logic</strong> (Reacting to state changes with effect())<br> ✔️ <strong>Zone.js-Free Components</strong> (Future-proofing your app)</p><p>🚀 <strong>Angular Signals are shaping the future of Angular state management!</strong> Have you tried them in your projects? Drop a comment below! 👇</p><p>#Angular #WebDevelopment #Angular17 #Signals #ReactiveProgramming #Frontend #TypeScript #Performance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2aebb3ecd33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>