<?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[ZestGeek - Medium]]></title>
        <description><![CDATA[ZestGeek Solution is a leading IT company that provide high quality and enterprise level solutions across wide range of platforms and technologies. - Medium]]></description>
        <link>https://medium.com/zestgeek?source=rss----16e54d2de185---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>ZestGeek - Medium</title>
            <link>https://medium.com/zestgeek?source=rss----16e54d2de185---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:16:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/zestgeek" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React Compiler: The End of Manual Memoization in React?]]></title>
            <link>https://medium.com/zestgeek/react-compiler-the-end-of-manual-memoization-in-react-26c07341168e?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/26c07341168e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 13:57:48 GMT</pubDate>
            <atom:updated>2026-03-31T14:00:44.369Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, performance optimization in <strong>React</strong> meant one thing:</p><p>Developers had to manually decide where to use:</p><ul><li>useMemo</li><li>useCallback</li><li>React.memo</li></ul><p>That often created two problems:</p><ol><li>Over-optimization in places where it was unnecessary</li><li>Missed optimizations in places where performance actually mattered</li></ol><p>Now, React is changing that model completely.</p><p>With the stable launch of <strong>React Compiler 1.0</strong>, the React team introduced a build-time optimization system that automatically understands component behavior and applies memoization for you.</p><p>This is not just another performance utility — it changes how React applications are written, reviewed, and scaled.</p><h3>What is React Compiler?</h3><p>React Compiler is a <strong>build-time optimizer</strong> that analyzes your React code before it runs in the browser.</p><p>Instead of waiting until runtime, it studies:</p><ul><li>component purity</li><li>props usage</li><li>state dependencies</li><li>render conditions</li><li>hook behavior</li></ul><p>Then it generates optimized output automatically.</p><p>In simple words:</p><blockquote><em>React Compiler decides when your component truly needs to re-render — and skips unnecessary work automatically.</em></blockquote><p>That means many manual memoization patterns become unnecessary.</p><h3>Why React Compiler Was Needed</h3><p>A common React component today looks like this:</p><pre>const filteredUsers = useMemo(() =&gt; {<br>  return users.filter(user =&gt; user.active);<br>}, [users]);</pre><p>And event handlers often look like this:</p><pre>const handleSave = useCallback(() =&gt; {<br>  submit(data);<br>}, [data]);</pre><p>This works, but it introduces developer burden:</p><ul><li>dependency arrays must stay correct</li><li>stale closures can happen</li><li>performance logic mixes with business logic</li></ul><p>React Compiler removes much of this manual effort.</p><h3>What React Compiler Improves</h3><h3>1. Automatic Memoization</h3><p>The compiler automatically applies optimizations similar to:</p><ul><li>useMemo</li><li>useCallback</li><li>React.memo</li></ul><p>without requiring explicit code changes.</p><p>This means cleaner components:</p><pre>function UserList({ users }) {<br>  const filteredUsers = users.filter(user =&gt; user.active);<br>  return &lt;List items={filteredUsers} /&gt;;<br>}</pre><p>The compiler can optimize this automatically.</p><h3>2. More Accurate Than Manual Optimization</h3><p>Manual memoization often misses complex render paths.</p><p>The compiler analyzes:</p><ul><li>nested branches</li><li>conditional rendering</li><li>internal data flow</li></ul><p>It can detect optimization opportunities humans often miss.</p><h3>3. Cleaner Codebase</h3><p>A major long-term advantage:</p><p>Your code becomes easier to read.</p><p>Less noise:</p><ul><li>fewer hooks for optimization</li><li>fewer dependency arrays</li><li>fewer review discussions around memoization</li></ul><p>This improves maintainability for large teams.</p><h3>4. Better Default Performance for Large Apps</h3><p>In large dashboards, admin panels, and enterprise apps, repeated re-renders become expensive.</p><p>Compiler benefits are stronger when:</p><ul><li>Many nested components exist</li><li>Large prop trees exist</li><li>Derived calculations happen frequently</li></ul><h3>What React Compiler Does NOT Replace</h3><p>Important: React Compiler is not magic.</p><p>It does <strong>not replace good architecture</strong>.</p><p>You still need:</p><ul><li>proper state design</li><li>normalized data flow</li><li>smart component boundaries</li></ul><p>It also does not fix:</p><ul><li>expensive network requests</li><li>poor effect logic</li><li>large DOM rendering bottlenecks</li></ul><h3>When You Should Use React Compiler</h3><p>Best fit:</p><p>✅ Medium to large React applications<br> ✅ Frequent re-render complexity<br> ✅ Teams are tired of excessive memoization<br> ✅ Shared component libraries<br> ✅ Long-term maintainable codebases</p><p>Especially useful for:</p><ul><li>SaaS dashboards</li><li>enterprise portals</li><li>product-heavy UIs</li><li>design systems</li></ul><h3>When You Should Be Careful</h3><p>Not every app needs immediate adoption.</p><p>Be cautious if:</p><ul><li>legacy patterns heavily violate the Rules of React</li><li>components contain side effects inside render</li><li>code relies on mutation-heavy logic</li></ul><p>Compiler depends heavily on React purity rules.</p><h3>Incremental Adoption: You Don’t Need Full Migration</h3><p>One of the strongest design decisions:</p><p>React Compiler supports gradual adoption.</p><p>You can enable it:</p><ul><li>per project</li><li>per module</li><li>gradually across teams</li></ul><p>React officially recommends incremental rollout for existing codebases.</p><p>This is ideal for production systems.</p><h3>How to Install React Compiler</h3><p>Basic setup:</p><pre>npm install babel-plugin-react-compiler</pre><p>Then configure inside Babel:</p><pre>plugins: [&#39;babel-plugin-react-compiler&#39;]</pre><p>Modern ecosystem support already exists for:</p><ul><li>Next.js</li><li>Vite</li><li>Expo</li></ul><p>Official tooling partnerships were announced with the React Compiler 1.0 launch.</p><h3>React Version Compatibility</h3><p>React Compiler works best with:</p><ul><li>React 19</li><li>also supports React 17 and 18</li></ul><p>But latest React versions provide the best compiler integration.</p><h3>Debugging React Compiler</h3><p>If something behaves unexpectedly:</p><h3>Common debugging steps</h3><h3>Check compiler diagnostics</h3><p>Compiler now integrates with ESLint.</p><p>New lint rules help detect:</p><ul><li>impure rendering</li><li>unsupported patterns</li><li>unsafe mutations</li></ul><h3>Verify Rules of React</h3><p>Compiler depends on:</p><ul><li>stable hook order</li><li>pure render logic</li><li>predictable state access</li></ul><h3>Use incremental rollout</h3><p>Disable compiler selectively where needed.</p><p>Official debugging guide strongly recommends targeted adoption first.</p><h3>Important Limitation: Compiler Only Optimizes Safe Code</h3><p>If code breaks React principles:</p><pre>items.push(newItem)</pre><p>Compiler may skip optimization.</p><p>Immutable patterns still matter.</p><p>Correct:</p><pre>const updated = [...items, newItem]</pre><h3>Will useMemo and useCallback Disappear?</h3><p>Not completely.</p><p>Some advanced cases still need manual control:</p><h3>Still useful when:</h3><ul><li>third-party memo-sensitive APIs exist</li><li>non-React expensive calculations happen</li><li>custom hook contracts require stable identity</li></ul><p>But most everyday memoization may become unnecessary.</p><p>That is a major mental shift for React developers.</p><h3>Biggest Real-World Impact for Teams</h3><p>For senior teams, biggest win is not speed alone.</p><p><strong>It is:</strong></p><h4>Fewer performance debates in pull requests</h4><p>Before:</p><blockquote><em>“Should this be wrapped in useCallback?”</em></blockquote><p>Now:</p><p>Compiler handles most of that automatically.</p><p>This reduces cognitive overhead significantly.</p><h3>Compiler-Powered Linting Is Underrated</h3><p>A very important launch addition:</p><p>Compiler intelligence now powers ESLint recommendations too.</p><p>This means:</p><p>The compiler doesn’t just optimize.</p><p>It teaches better React patterns.</p><h3>My Practical Recommendation</h3><p><strong>If you maintain:</strong></p><ul><li>product code</li><li>internal dashboard systems</li><li>long-lived React applications</li></ul><p>React Compiler is worth testing now.</p><p><strong>Best path:</strong></p><h4>Start with one feature module</h4><p>Measure:</p><ul><li>render frequency</li><li>bundle behavior</li><li>lint warnings</li><li>team comfort</li></ul><p>Then expand gradually.</p><h3>Final Thought</h3><p>React Compiler is one of the most important architectural shifts since Hooks.</p><p>Hooks changed how we manage logic.</p><p>Compiler changes how we think about performance.</p><p>For years React asked developers to manually optimize.</p><p>Now React finally starts doing that work itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c07341168e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/react-compiler-the-end-of-manual-memoization-in-react-26c07341168e">React Compiler: The End of Manual Memoization in React?</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Vibe Coding and Its Impact on Developers]]></title>
            <link>https://medium.com/zestgeek/ai-vibe-coding-and-its-impact-on-developers-dd986a2a748c?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd986a2a748c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 12:22:02 GMT</pubDate>
            <atom:updated>2025-07-30T12:20:27.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmvTIuzovFlxnN1824a8pg.png" /><figcaption>AI Vibe Coding and Its Impact on Developers</figcaption></figure><p>Imagine you’re coding, and everything just clicks. Your fingers fly, ideas flow, and you’re totally in sync with your project. That’s “vibe coding.” Now, picture that same feeling, but with a super-smart AI buddy right there, helping you every step of the way. That’s <strong>AI Vibe Coding</strong>.</p><p>It’s not just about getting more done; it’s about <em>enjoying</em> the process of getting more done.</p><h3>What Exactly is AI Vibe Coding?</h3><p>“Vibe coding” used to mean those comfy, focused coding sessions — think lo-fi music, a warm drink, and a great groove. But with AI tools becoming commonplace, a new kind of “vibe” has emerged.</p><p><strong>AI Vibe Coding</strong> is when you’re coding with the help of AI tools like GitHub Copilot or ChatGPT, and it feels like you’re perfectly in sync with a brilliant coding partner. The AI helps finish your thoughts, writes handy functions, spots bugs, and keeps you immersed in your work.</p><h3>How AI Makes Coding More Enjoyable</h3><p>With an AI assistant, you won’t get stuck on the boring bits like writing repetitive code, endlessly searching for syntax, or fixing silly typos. Here’s how AI changes the game:</p><ul><li><strong>Less Frustration:</strong> Just tell the AI what you want in plain English, and it writes the code for you.</li><li><strong>Instant Help:</strong> No more waiting or switching tabs; your AI buddy is right there when you need it.</li><li><strong>Fewer Distractions:</strong> You stay focused in your coding environment, without jumping between documentation or Stack Overflow.</li></ul><p>It’s like having a genius, non-judgmental pair programmer who never gets tired!</p><h3>Tools That Power the AI Vibe</h3><p>Developers are using several popular AI tools to get into that flow state:</p><ul><li><strong>GitHub Copilot:</strong> Suggests entire lines and functions as you type.</li><li><strong>ChatGPT (like me!):</strong> Great for asking “why,” brainstorming ideas, or refining your code’s logic.</li><li><strong>Amazon CodeWhisperer:</strong> Another strong assistant that provides real-time suggestions.</li><li><strong>Cursor:</strong> This AI-first code editor integrates AI directly into your workflow, offering smart autocompletion, chat with your codebase, and even “agent mode” to complete complex tasks across multiple files.</li><li><strong>Windsurf:</strong> An AI agent IDE that focuses on “intent-driven coding.” It goes beyond simple suggestions, helping you build and iterate on entire applications, even running scripts and automatically fixing errors.</li><li><strong>Custom AI agents:</strong> Some developers even train their own mini-AIs tailored to their specific code.</li></ul><p>These tools aren’t just extras anymore; they’re becoming fundamental to how we think and create software.</p><h3>Boost Your Flow, Focus, and Creativity</h3><p>One of the best perks of AI vibe coding is that it helps you stay in that magical “flow” state — where time flies by, and problems seem to solve themselves. Here’s how AI helps:</p><ul><li>When you’re stuck, the AI offers solutions to get you moving again.</li><li>You can quickly explore different ideas without worrying about breaking your code.</li><li>You feel more confident experimenting because the AI has your back.</li></ul><p>It shifts the focus from “writing perfect code” to thinking creatively with code.</p><h3>The Not-So-Sunny Side of the Vibe</h3><p>Of course, it’s not always smooth sailing. Some developers do have concerns about AI vibe coding:</p><ul><li><strong>Getting too reliant:</strong> Depending too much on AI might make your core coding skills rusty.</li><li><strong>Wrong answers:</strong> AI isn’t perfect; it can sometimes give you incorrect or misleading suggestions.</li><li><strong>Distractions:</strong> If you’re not careful, the AI could interrupt your thought process instead of helping it.</li></ul><p>The trick is to use AI as a valuable partner, not a crutch.</p><h3>How Developers Are Embracing the Vibe</h3><p>Many developers are now setting up their coding spaces to maximize the AI vibe:</p><ul><li>Playing calming music and using cool themes in their coding environment.</li><li>Having Copilot, ChatGPT, Cursor, or Windsurf running alongside their work.</li><li>Using smart code snippets and automated workflows.</li><li>Some even stream their coding sessions, showing how they work live with AI.</li></ul><p>For more and more developers, AI is becoming an essential part of their coding routine — it’s part of the whole experience.</p><h3>The Future of AI Vibe Coding</h3><p>Looking ahead, AI vibe coding is set to evolve even further:</p><ul><li>Your AI will learn your personal coding style and suggest code that truly feels like <em>you</em> wrote it.</li><li>You’ll spend less time on basic syntax and more time shaping innovative ideas.</li><li>Coding might feel more like designing or storytelling, with AI handling the technical details.</li></ul><p>Imagine saying, “Build me a chatbot that helps users reset their password,” and seeing it come to life in minutes. That’s not science fiction; that’s where we’re headed.</p><h3>Final Thoughts</h3><p>AI vibe coding is more than just a passing trend; it’s changing how we feel about building software. It’s transforming coding from a solitary, sometimes frustrating task into a smoother, more enjoyable, and collaborative journey. Whether you’re new to coding or a seasoned pro, there’s something genuinely human about coding with an AI — because it lets us focus on what we truly love: solving problems, creating awesome things, and having fun along the way.</p><p>So, next time you code, set the mood, fire up your AI assistant, and feel the vibe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd986a2a748c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/ai-vibe-coding-and-its-impact-on-developers-dd986a2a748c">AI Vibe Coding and Its Impact on Developers</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular Signals: A Comprehensive Guide with Working Examples]]></title>
            <link>https://medium.com/zestgeek/understanding-angular-signals-a-comprehensive-guide-with-working-examples-559c1b03cd2b?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/559c1b03cd2b</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 08:02:49 GMT</pubDate>
            <atom:updated>2025-04-03T08:13:32.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzxA_0kKiAbsPn_BKe5f7Q.png" /></figure><h3>Introduction</h3><p>Angular Signals, introduced in Angular 16, represent a fundamental shift in how we handle reactivity in Angular applications. Unlike the traditional change detection mechanisms, Signals provide a more fine-grained, efficient, and intuitive way to manage state and propagate changes throughout your application.</p><p>In this article, we’ll explore what Signals are, how they work, and provide multiple working examples to demonstrate their power and flexibility.</p><h3>What Are Angular Signals?</h3><p>A Signal is a wrapper around a value that can notify interested consumers when that value changes. The key attributes of Signals include:</p><ol><li><strong>Reactivity</strong>: Signals automatically track dependencies and update only what’s necessary</li><li><strong>Fine-grained change detection</strong>: Only components that depend on a changed Signal value will update</li><li><strong>Synchronous updates</strong>: Changes propagate immediately through the dependency graph</li><li><strong>Type safety</strong>: Signals are fully typed in TypeScript</li></ol><h3>Core Signal APIs</h3><p>Let’s start with the basic building blocks:</p><pre>// Creating a signal with an initial value<br>const count = signal(0);<br><br>// Reading a signal&#39;s value<br>console.log(count()); // 0<br><br>// Setting a new value<br>count.set(5);<br><br>// Updating based on previous value<br>count.update(value =&gt; value + 1);</pre><h3>Basic Example: Counter Component</h3><p>Here’s a simple counter component that uses Signals:</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {{ count() }}&lt;/h2&gt;<br>      &lt;button (click)=&quot;increment()&quot;&gt;Increment&lt;/button&gt;<br>      &lt;button (click)=&quot;decrement()&quot;&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class CounterComponent {<br>  count = signal(0);<br><br>  increment() {<br>    this.count.update(value =&gt; value + 1);<br>  }<br><br>  decrement() {<br>    this.count.update(value =&gt; value - 1);<br>  }<br>}</pre><h3>Computed Signals</h3><p>Computed signals derive their value from other signals automatically:</p><pre>import { Component, signal, computed } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-temperature-converter&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Temperature Converter&lt;/h2&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Celsius: &lt;/label&gt;<br>        &lt;input type=&quot;number&quot; [value]=&quot;celsius()&quot; (input)=&quot;updateCelsius($event)&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Fahrenheit: &lt;/label&gt;<br>        &lt;span&gt;{{ fahrenheit() }}&lt;/span&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class TemperatureConverterComponent {<br>  celsius = signal(0);<br>  fahrenheit = computed(() =&gt; this.celsius() * 9/5 + 32);<br><br>  updateCelsius(event: Event) {<br>    const value = +(event.target as HTMLInputElement).value;<br>    this.celsius.set(value);<br>  }<br>}</pre><h3>Effects: Reacting to Signal Changes</h3><p>Effects allow you to perform side effects when signals change:</p><pre>import { Component, signal, effect } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-logger&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Logger Example&lt;/h2&gt;<br>      &lt;input [value]=&quot;message()&quot; (input)=&quot;updateMessage($event)&quot;&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class LoggerComponent {<br>  message = signal(&#39;Hello World&#39;);<br><br>  constructor() {<br>    effect(() =&gt; {<br>      console.log(`Message changed to: ${this.message()}`);<br>    });<br>  }<br><br>  updateMessage(event: Event) {<br>    const value = (event.target as HTMLInputElement).value;<br>    this.message.set(value);<br>  }<br>}</pre><h3>Working with Objects and Arrays</h3><p>Signals can contain complex data structures. Here’s how to work with them properly:</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br><br>interface User {<br>  name: string;<br>  email: string;<br>}<br><br>@Component({<br>  selector: &#39;app-user-form&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;User Info&lt;/h2&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Name: &lt;/label&gt;<br>        &lt;input [value]=&quot;user().name&quot; (input)=&quot;updateName($event)&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;Email: &lt;/label&gt;<br>        &lt;input [value]=&quot;user().email&quot; (input)=&quot;updateEmail($event)&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;button (click)=&quot;resetUser()&quot;&gt;Reset&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class UserFormComponent {<br>  user = signal&lt;User&gt;({ name: &#39;&#39;, email: &#39;&#39; });<br><br>  updateName(event: Event) {<br>    const name = (event.target as HTMLInputElement).value;<br>    this.user.update(user =&gt; ({ ...user, name }));<br>  }<br><br>  updateEmail(event: Event) {<br>    const email = (event.target as HTMLInputElement).value;<br>    this.user.update(user =&gt; ({ ...user, email }));<br>  }<br><br>  resetUser() {<br>    this.user.set({ name: &#39;&#39;, email: &#39;&#39; });<br>  }<br>}</pre><h3>Todo List Example: Putting It All Together</h3><p>This example demonstrates using Signals with arrays and complex operations:</p><pre>import { Component, signal, computed } from &#39;@angular/core&#39;;<br><br>interface Todo {<br>  id: number;<br>  text: string;<br>  completed: boolean;<br>}<br><br>@Component({<br>  selector: &#39;app-todo-list&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Todo List&lt;/h2&gt;<br>      &lt;div&gt;<br>        &lt;input #newTodo placeholder=&quot;Add todo&quot; <br>               (keyup.enter)=&quot;addTodo(newTodo.value); newTodo.value = &#39;&#39;&quot;&gt;<br>        &lt;button (click)=&quot;addTodo(newTodo.value); newTodo.value = &#39;&#39;&quot;&gt;Add&lt;/button&gt;<br>      &lt;/div&gt;<br>      <br>      &lt;ul&gt;<br>        &lt;li *ngFor=&quot;let todo of todos()&quot;&gt;<br>          &lt;input type=&quot;checkbox&quot; <br>                 [checked]=&quot;todo.completed&quot; <br>                 (change)=&quot;toggleTodo(todo.id)&quot;&gt;<br>          &lt;span [style.text-decoration]=&quot;todo.completed ? &#39;line-through&#39; : &#39;none&#39;&quot;&gt;<br>            {{ todo.text }}<br>          &lt;/span&gt;<br>          &lt;button (click)=&quot;removeTodo(todo.id)&quot;&gt;Delete&lt;/button&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>      <br>      &lt;div&gt;<br>        &lt;p&gt;Remaining: {{ remainingCount() }}&lt;/p&gt;<br>        &lt;button (click)=&quot;clearCompleted()&quot;&gt;Clear Completed&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class TodoListComponent {<br>  todos = signal&lt;Todo[]&gt;([]);<br>  nextId = signal(1);<br>  <br>  remainingCount = computed(() =&gt; <br>    this.todos().filter(todo =&gt; !todo.completed).length<br>  );<br><br>  addTodo(text: string) {<br>    if (!text.trim()) return;<br>    <br>    this.todos.update(todos =&gt; [<br>      ...todos,<br>      { id: this.nextId(), text, completed: false }<br>    ]);<br>    this.nextId.update(id =&gt; id + 1);<br>  }<br><br>  toggleTodo(id: number) {<br>    this.todos.update(todos =&gt; <br>      todos.map(todo =&gt; <br>        todo.id === id ? { ...todo, completed: !todo.completed } : todo<br>      )<br>    );<br>  }<br><br>  removeTodo(id: number) {<br>    this.todos.update(todos =&gt; todos.filter(todo =&gt; todo.id !== id));<br>  }<br><br>  clearCompleted() {<br>    this.todos.update(todos =&gt; todos.filter(todo =&gt; !todo.completed));<br>  }<br>}</pre><h3>Advanced Usage: Signal Equality Functions</h3><p>By default, Signals use reference equality to determine if a value has changed. You can customize this behavior:</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br><br>interface Point {<br>  x: number;<br>  y: number;<br>}<br><br>function pointEquals(a: Point, b: Point): boolean {<br>  return a.x === b.x &amp;&amp; a.y === b.y;<br>}<br><br>@Component({<br>  selector: &#39;app-point-tracker&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Point: ({{ point().x }}, {{ point().y }})&lt;/h2&gt;<br>      &lt;button (click)=&quot;moveRight()&quot;&gt;Move Right&lt;/button&gt;<br>      &lt;button (click)=&quot;moveDown()&quot;&gt;Move Down&lt;/button&gt;<br>      &lt;button (click)=&quot;resetPoint()&quot;&gt;Reset&lt;/button&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class PointTrackerComponent {<br>  point = signal&lt;Point&gt;({ x: 0, y: 0 }, { equal: pointEquals });<br><br>  moveRight() {<br>    this.point.update(p =&gt; ({ ...p, x: p.x + 1 }));<br>  }<br><br>  moveDown() {<br>    this.point.update(p =&gt; ({ ...p, y: p.y + 1 }));<br>  }<br><br>  resetPoint() {<br>    // Even with same content, this will be detected as different<br>    // if we didn&#39;t use the custom equality function<br>    this.point.set({ x: 0, y: 0 });<br>  }<br>}</pre><h3>Integrating with RxJS</h3><p>Signals can work seamlessly with RxJS:</p><pre>import { Component, signal, inject, OnInit, OnDestroy } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br><br>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;User List&lt;/h2&gt;<br>      &lt;div *ngIf=&quot;loading()&quot;&gt;Loading...&lt;/div&gt;<br>      &lt;ul *ngIf=&quot;!loading()&quot;&gt;<br>        &lt;li *ngFor=&quot;let user of users()&quot;&gt;<br>          {{ user.name }} ({{ user.email }})<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>      &lt;div *ngIf=&quot;error()&quot;&gt;<br>        Error: {{ error() }}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class UserListComponent implements OnInit, OnDestroy {<br>  private http = inject(HttpClient);<br>  private subscription: Subscription | null = null;<br><br>  users = signal&lt;User[]&gt;([]);<br>  loading = signal(false);<br>  error = signal&lt;string | null&gt;(null);<br><br>  ngOnInit() {<br>    this.loading.set(true);<br>    this.subscription = this.http.get&lt;User[]&gt;(&#39;https://jsonplaceholder.typicode.com/users&#39;)<br>      .subscribe({<br>        next: (data) =&gt; {<br>          this.users.set(data);<br>          this.loading.set(false);<br>        },<br>        error: (err) =&gt; {<br>          this.error.set(err.message);<br>          this.loading.set(false);<br>        }<br>      });<br>  }<br><br>  ngOnDestroy() {<br>    this.subscription?.unsubscribe();<br>  }<br>}</pre><h3>Converting RxJS Observables to Signals</h3><p>Angular provides a utility to convert Observables to Signals:</p><pre>import { Component, inject, signal, computed } from &#39;@angular/core&#39;;<br>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br>import { interval } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;app-timer&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Timer: {{ formattedTime() }}&lt;/h2&gt;<br>    &lt;/div&gt;<br>  `,<br>})<br>export class TimerComponent {<br>  // Convert Observable to Signal<br>  private seconds = toSignal(<br>    interval(1000).pipe(map(i =&gt; i + 1)),<br>    { initialValue: 0 }<br>  );<br>  <br>  formattedTime = computed(() =&gt; {<br>    const totalSeconds = this.seconds();<br>    const minutes = Math.floor(totalSeconds / 60);<br>    const seconds = totalSeconds % 60;<br>    return `${minutes}:${seconds.toString().padStart(2, &#39;0&#39;)}`;<br>  });<br>}</pre><h3>Performance Benefits of Signals</h3><p>Signals provide significant performance improvements over the traditional change detection:</p><ol><li><strong>Reduced template checks</strong>: Only templates that directly consume changed signals are checked</li><li><strong>Granular updates</strong>: Only the specific parts of the template that depend on changed signals update</li><li><strong>Predictable change propagation</strong>: Changes flow in one direction through the dependency graph</li></ol><h3>Best Practices for Using Signals</h3><ol><li><strong>Keep signal values immutable</strong>: Always create new references when updating objects or arrays</li><li><strong>Use computed signals for derived state</strong>: Instead of calculating values in templates</li><li><strong>Minimize side effects</strong>: Use effects only when necessary for side effects like logging or saving to storage</li><li><strong>Create signals at appropriate levels</strong>: Place signals at the right component level to minimize prop drilling</li><li><strong>Use custom equality functions</strong>: For complex objects when reference equality isn’t sufficient</li></ol><h3>Conclusion</h3><p>Angular Signals provide a powerful new paradigm for managing state and reactivity in Angular applications. They offer improved performance, more intuitive state management, and better developer experience compared to traditional change detection.</p><p>By leveraging signals for both simple and complex use cases, you can build more responsive, maintainable, and efficient Angular applications.</p><p>The examples provided in this article demonstrate how signals can be used in various scenarios, from simple counters to complex data manipulation, and how they integrate with other Angular features and libraries like RxJS.</p><p>As Angular continues to evolve, Signals are poised to become a central part of the framework’s reactivity model, making it essential for developers to understand and adopt this powerful feature.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=559c1b03cd2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/understanding-angular-signals-a-comprehensive-guide-with-working-examples-559c1b03cd2b">Understanding Angular Signals: A Comprehensive Guide with Working Examples</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Angular 18 to Angular 19: A Step-by-Step Guide]]></title>
            <link>https://medium.com/zestgeek/upgrading-angular-18-to-angular-19-a-step-by-step-guide-420867e551df?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/420867e551df</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 10:55:24 GMT</pubDate>
            <atom:updated>2025-03-25T13:01:08.334Z</atom:updated>
            <content:encoded><![CDATA[<p>Upgrading your Angular application ensures that you stay up-to-date with the latest features, performance improvements, security patches, and bug fixes. Angular 19 introduces <strong>Standalone Components by Default, Incremental Hydration, TypeScript 5.6 support, and various performance optimizations.</strong></p><p>This guide provides a <strong>detailed, step-by-step process</strong> to upgrade your Angular 18 project to Angular 19 successfully.</p><h3>Step 1: Review Angular 19 Release Notes</h3><p>Before proceeding with the upgrade, it’s important to review the <a href="https://github.com/angular/angular/blob/main/CHANGELOG.md">Angular 19 changelog</a> to understand new features, deprecations, and potential breaking changes. Some key highlights include:</p><ul><li><strong>Standalone Components by Default</strong>: Angular now treats directives, pipes, and components as standalone by default. If you still use NgModules, you must manually set standalone: false.</li><li><strong>Incremental Hydration</strong>: New hydration strategies improve Server-Side Rendering (SSR) by lazily hydrating templates.</li><li><strong>TypeScript 5.6 Support</strong>: Angular 19 supports TypeScript 5.6, allowing you to use the latest TypeScript features.</li><li><strong>Performance Optimizations</strong>: Improvements in rendering, change detection, and module resolution enhance performance.</li></ul><h3>Step 2: Backup Your Project</h3><p>Before making any changes, ensure you <strong>backup your project</strong> or have it under <strong>Git version control.</strong></p><h3>Step 3: Update Global Angular CLI</h3><p>Ensure you have the latest Angular CLI globally installed by running:</p><pre>npm install -g @angular/cli@19</pre><p>Verify the installed version:</p><pre>ng version</pre><h3>Step 4: Upgrade Angular in Your Project</h3><p>Run the following command inside your project directory to update the core Angular packages:</p><pre>ng update @angular/cli@19 @angular/core@19 --force</pre><p>This will:<br>✅ Automatically apply necessary migrations<br>✅ Update dependencies in package.json<br>✅ Handle breaking changes</p><p>⚠️ If you encounter errors, try using --force, but review changes carefully.</p><h3>Step 5: Update TypeScript Version</h3><p>Since Angular 19 supports TypeScript 5.6, update it manually:</p><pre>npm install typescript@5.6 --save-dev</pre><p>Verify the version:</p><pre>npx tsc -v</pre><h3>Step 6: Update Other Angular Dependencies</h3><p>You may also need to update other Angular packages such as:</p><pre>ng update @angular/forms @angular/router @angular/platform-browser @angular/platform-browser-dynamic</pre><p>If your project uses Angular Material, update it as well:</p><pre>ng update @angular/material</pre><h3>Step 7: Update Third-Party Dependencies</h3><p>Some third-party packages might not be compatible with Angular 19. Run:</p><pre>npm outdated</pre><p>To update packages, use:</p><pre>npm install package-name@latest</pre><h3>Step 8: Fix Breaking Changes and Deprecations</h3><p>Check your code for breaking changes, especially:</p><ul><li><strong>Standalone Components</strong>: If you rely on NgModules, set standalone: false.</li><li><strong>Hydration Updates</strong>: If using SSR, update hydration logic to align with incremental hydration.</li><li><strong>Router Changes</strong>: If using lazy loading, verify that module imports work correctly.</li></ul><h3>Step 9: Run and Test the Application</h3><p>After upgrading dependencies, test your application thoroughly:</p><ul><li><strong>Check if the app compiles correctly</strong>:</li></ul><pre>ng serve</pre><ul><li><strong>Run unit tests</strong>:</li></ul><pre>ng test</pre><ul><li><strong>Run end-to-end tests</strong> (if applicable):</li></ul><pre>ng e2e</pre><ul><li><strong>Manually verify key features</strong> to ensure everything works as expected.</li></ul><h3>Step 10: Optimize Build Configurations</h3><p>After upgrading, fine-tune your angular.json and tsconfig.json files:</p><h3>Update angular.json</h3><p>Ensure your build settings match Angular 19’s best practices:</p><pre>&quot;optimization&quot;: true,<br>&quot;sourceMap&quot;: false,</pre><h3>Update tsconfig.json</h3><p>Ensure compatibility with TypeScript 5.6:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2022&quot;,<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>    &quot;strict&quot;: true<br>  }<br>}</pre><h3>Step 11: Perform a Production Build</h3><p>Once everything works locally, create a production build:</p><pre>ng build --configuration=production</pre><p>If using SSR:</p><pre>ng run my-app:server</pre><h3>Step 12: Deploy and Monitor</h3><p>Now, deploy your upgraded Angular 19 application to your production environment.<br>✅ <strong>Push changes to Git</strong><br>✅ <strong>Monitor logs for potential issues</strong><br>✅ <strong>Check performance improvements</strong></p><h3>Conclusion</h3><p>Upgrading to Angular 19 provides <strong>better performance, SSR hydration improvements, and TypeScript 5.6 support.</strong> Following this step-by-step guide ensures a <strong>smooth migration</strong> while leveraging <strong>new features and enhancements</strong>. 🚀</p><p>Are you planning to upgrade your Angular app? Let me know your thoughts or any issues you face! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420867e551df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/upgrading-angular-18-to-angular-19-a-step-by-step-guide-420867e551df">Upgrading Angular 18 to Angular 19: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Tailwind CSS in an Expo React Native Project: A Step-by-Step Guide]]></title>
            <link>https://medium.com/zestgeek/setting-up-tailwind-css-in-an-expo-react-native-project-a-step-by-step-guide-eab8ff5c0759?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/eab8ff5c0759</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[tailwind]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 10:26:09 GMT</pubDate>
            <atom:updated>2025-01-22T10:25:34.464Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tailwind CSS</strong> is a popular utility-first CSS framework that simplifies styling by providing a set of predefined classes. While primarily designed for web development, Tailwind CSS can be used in <strong>React Native</strong> projects with libraries like tailwindcss-react-native. This guide walks you through setting up Tailwind in an <strong>Expo React Native</strong> project.</p><h3>Prerequisites</h3><p>Before we begin, ensure you have the following:</p><ul><li>Node.js installed</li><li>Expo CLI set up</li><li>Basic understanding of React Native and Expo</li></ul><h3>Step 1: Create a New Expo Project</h3><p>Run the following command to create a new Expo project:</p><pre>npx create-expo-app my-tailwind-app  <br>cd my-tailwind-app</pre><p>Start the development server to ensure everything is set up correctly:</p><pre>npx expo start</pre><h3>Step 2: Install Dependencies</h3><p>To use Tailwind CSS in React Native, we’ll use tailwindcss-react-native. Install the required packages:</p><pre>npm install tailwindcss tailwindcss-react-native postcss</pre><p>Install additional dependencies for PostCSS:</p><pre>npm install autoprefixer</pre><h3>Step 3: Initialize Tailwind CSS</h3><p>Run the following command to create the Tailwind CSS configuration file:</p><pre>npx tailwindcss init</pre><p>This will generate a tailwind.config.js file in the root directory.</p><h3>Setting Up Tailwind CSS in an Expo React Native Project: A Step-by-Step Guide</h3><p>Run the following command to create a new Expo project:</p><pre>bash</pre><pre>CopyEdit</pre><pre>npx create-expo-app my-tailwind-app  <br>cd my-tailwind-app</pre><p>Start the development server to ensure everything is set up correctly:</p><pre>bash</pre><pre>CopyEdit</pre><pre>npx expo start</pre><h3>Step 2: Install Dependencies</h3><p>To use Tailwind CSS in React Native, we’ll use tailwindcss-react-native. Install the required packages:</p><pre>bash</pre><pre>CopyEdit</pre><pre>npm install tailwindcss tailwindcss-react-native postcss</pre><p>Install additional dependencies for PostCSS:</p><pre>bash</pre><pre>CopyEdit</pre><pre>npm install autoprefixer</pre><h3>Step 3: Initialize Tailwind CSS</h3><p>Run the following command to create the Tailwind CSS configuration file:</p><pre>bash</pre><pre>CopyEdit</pre><pre>npx tailwindcss init</pre><p>This will generate a tailwind.config.js file in the root directory.</p><h3>Step 4: Configure Tailwind for React Native</h3><p>Modify the tailwind.config.js file to include tailwindcss-react-native and specify your custom styles:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab8ff5c0759" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/setting-up-tailwind-css-in-an-expo-react-native-project-a-step-by-step-guide-eab8ff5c0759">Setting Up Tailwind CSS in an Expo React Native Project: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Custom Chatbot with OpenAI GPT-4.0 and Next.js (App Router)]]></title>
            <link>https://medium.com/zestgeek/building-your-custom-chatbot-with-openai-gpt-4-0-and-next-js-app-router-909914e97125?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/909914e97125</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 10:54:11 GMT</pubDate>
            <atom:updated>2025-01-16T10:19:01.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Chatbots are no longer a luxury — they’re essential for modern applications to enhance customer experience, automate support, and deliver real-time solutions. With OpenAI GPT-4.0 and the latest Next.js App Router, you can build a powerful, conversational chatbot tailored to your needs.</p><p>This article guides you through creating a chatbot using <strong>Next.js’s App Router</strong> and <strong>OpenAI GPT-4.0</strong> with step-by-step code examples.</p><h3>Why Choose GPT-4.0 and Next.js App Router?</h3><ul><li><strong>GPT-4.0</strong>: Advanced conversational abilities with better contextual understanding.</li><li><strong>Next.js App Router</strong>: Simplified routing structure and better data-fetching mechanisms for server and client components.</li></ul><h3>Getting Started</h3><h3>Prerequisites</h3><ol><li><strong>Node.js &gt;= 18.x</strong></li><li><strong>OpenAI API Key</strong> (<a href="https://platform.openai.com/signup/">Get it here</a>)</li><li>Basic understanding of React and Next.js</li></ol><h3>Step 1: Initialize a New Next.js Project</h3><p>First, create a new Next.js application:</p><pre>npx create-next-app@latest custom-chatbot --ts  <br>cd custom-chatbot</pre><p>Enable the new <strong>App Router</strong> by default.</p><h3>Step 2: Install Required Dependencies</h3><p>Install the OpenAI library for interacting with the API:</p><pre>npm install openai</pre><h3>Step 3: Configure Environment Variables</h3><p>Create a .env.local file in the root directory and add your OpenAI API key:</p><pre>OPENAI_API_KEY=your-openai-api-key</pre><h3>Step 4: Set Up the API Route</h3><p>With the App Router, API routes are placed under the app/api directory. Create a new file at app/api/chat/route.js:</p><pre>// app/api/chat/route.js<br>import { Configuration, OpenAIApi } from &quot;openai&quot;;<br><br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>const openai = new OpenAIApi(configuration);<br><br>export async function POST(req) {<br>  try {<br>    const body = await req.json();<br>    const { messages } = body;<br><br>    const response = await openai.createChatCompletion({<br>      model: &quot;gpt-4&quot;,<br>      messages,<br>    });<br><br>    return new Response(JSON.stringify({ reply: response.data.choices[0].message.content }), {<br>      status: 200,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    });<br>  } catch (error) {<br>    console.error(error);<br>    return new Response(JSON.stringify({ error: &quot;Failed to fetch response from OpenAI&quot; }), {<br>      status: 500,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    });<br>  }<br>}</pre><h3>Step 5: Build the Chat Interface</h3><p>The app/page.js file serves as the main page in the App Router. Use it to create the chatbot interface:</p><pre>&quot;use client&quot;;<br><br>import { useState } from &quot;react&quot;;<br><br>export default function Home() {<br>  const [messages, setMessages] = useState([]);<br>  const [input, setInput] = useState(&quot;&quot;);<br><br>  const sendMessage = async () =&gt; {<br>    if (!input.trim()) return;<br><br>    const newMessages = [...messages, { role: &quot;user&quot;, content: input }];<br>    setMessages(newMessages);<br>    setInput(&quot;&quot;);<br><br>    try {<br>      const res = await fetch(&quot;/api/chat&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify({ messages: newMessages }),<br>      });<br><br>      const data = await res.json();<br><br>      if (res.ok) {<br>        setMessages([...newMessages, { role: &quot;assistant&quot;, content: data.reply }]);<br>      } else {<br>        console.error(data.error);<br>      }<br>    } catch (error) {<br>      console.error(&quot;Error:&quot;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;min-h-screen p-8 bg-gray-100&quot;&gt;<br>      &lt;div className=&quot;max-w-xl mx-auto bg-white p-6 rounded shadow&quot;&gt;<br>        &lt;h1 className=&quot;text-2xl font-bold mb-4&quot;&gt;Chatbot with GPT-4.0&lt;/h1&gt;<br>        &lt;div className=&quot;space-y-4&quot;&gt;<br>          {messages.map((msg, index) =&gt; (<br>            &lt;div<br>              key={index}<br>              className={`p-3 rounded ${<br>                msg.role === &quot;user&quot; ? &quot;bg-blue-100 text-blue-900&quot; : &quot;bg-gray-100 text-gray-900&quot;<br>              }`}<br>            &gt;<br>              &lt;strong&gt;{msg.role === &quot;user&quot; ? &quot;You&quot; : &quot;Bot&quot;}:&lt;/strong&gt; {msg.content}<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>        &lt;div className=&quot;mt-4 flex&quot;&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            value={input}<br>            onChange={(e) =&gt; setInput(e.target.value)}<br>            placeholder=&quot;Type your message...&quot;<br>            className=&quot;flex-1 p-2 border border-gray-300 rounded-l&quot;<br>          /&gt;<br>          &lt;button<br>            onClick={sendMessage}<br>            className=&quot;px-4 py-2 bg-blue-500 text-white rounded-r&quot;<br>          &gt;<br>            Send<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Step 6: Style the Chatbot</h3><p>Install <strong>Tailwind CSS</strong> for styling:</p><pre>npm install -D tailwindcss postcss autoprefixer  <br>npx tailwindcss init</pre><p>Configure tailwind.config.js:</p><pre>module.exports = {<br>  content: [&quot;./app/**/*.{js,ts,jsx,tsx}&quot;],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>};</pre><p>Add Tailwind’s styles in app/globals.css:</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><h3>Final Touch: Run the Chatbot</h3><p>Start the development server:</p><pre>npm run dev</pre><p>Visit http://localhost:3000 to interact with your custom GPT-4.0 chatbot!</p><h3>Key Takeaways</h3><ol><li><strong>Scalability</strong>: Easily expand the chatbot’s functionality using Next.js’s modular structure.</li><li><strong>Customizability</strong>: Fine-tune GPT-4.0’s responses by modifying prompts.</li><li><strong>Modern Development</strong>: Leverage Next.js App Router for seamless server-client communication.</li></ol><p>With just a few steps, you’ve created a custom chatbot that can enhance user engagement and streamline workflows. 🚀</p><p><strong>Looking to take it further?</strong><br>Integrate your chatbot with databases, authentication, or real-time communication for advanced use cases.</p><p>Happy coding! 👨‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909914e97125" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/building-your-custom-chatbot-with-openai-gpt-4-0-and-next-js-app-router-909914e97125">Building Your Custom Chatbot with OpenAI GPT-4.0 and Next.js (App Router)</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate shadcn into Next.js 14: A Step-by-Step Guide]]></title>
            <link>https://medium.com/zestgeek/how-to-integrate-shadcn-into-next-js-14-a-step-by-step-guide-917bb1946cba?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/917bb1946cba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 10:26:21 GMT</pubDate>
            <atom:updated>2025-01-09T10:25:49.798Z</atom:updated>
            <content:encoded><![CDATA[<p>ShadCN is a popular UI component library that combines utility-first styling with a robust design system. Pairing it with <strong>Next.js 14</strong> allows developers to build dynamic and performant web applications with clean and reusable components.</p><p>This guide walks you through the process of integrating <strong>ShadCN</strong> into <strong>Next.js 14</strong>, complete with step-by-step instructions and detailed coding examples.</p><h3>Why ShadCN?</h3><p>Before diving in, let’s understand why ShadCN is worth considering:</p><ul><li><strong>Customizable Components</strong>: Prebuilt but highly customizable.</li><li><strong>TypeScript Support</strong>: Designed with TypeScript for type safety.</li><li><strong>Tailwind CSS Friendly</strong>: Seamlessly integrates with Tailwind for utility-based styling.</li><li><strong>Accessibility</strong>: Ensures components are accessible out of the box.</li></ul><h3>Prerequisites</h3><p>Before starting, ensure the following:</p><ol><li>Node.js &gt;= 18.x</li><li>Next.js 14 installed in your project</li><li>Tailwind CSS configured (we’ll cover this)</li><li>Basic knowledge of React and TypeScript</li></ol><h3>Step 1: Set Up a New Next.js 14 Project</h3><p>If you don’t have a Next.js project yet, create one using the Next.js CLI.</p><pre>npx create-next-app@latest my-next-app --typescript<br>cd my-next-app</pre><h3>Step 2: Install Tailwind CSS</h3><p>ShadCN heavily relies on Tailwind CSS. Follow these steps to set it up:</p><h3>Install Tailwind Dependencies</h3><pre>npm install -D tailwindcss postcss autoprefixer<br>npx tailwindcss init</pre><h3>Configure Tailwind</h3><p>Update the tailwind.config.js file:</p><pre>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [<br>    &#39;./pages/**/*.{js,ts,jsx,tsx}&#39;,<br>    &#39;./components/**/*.{js,ts,jsx,tsx}&#39;,<br>    &#39;./app/**/*.{js,ts,jsx,tsx}&#39;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>};</pre><p>Add Tailwind imports in styles/globals.css:</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>Run the development server to verify the setup:</p><pre>npm run dev</pre><h3>Step 3: Install ShadCN</h3><p>ShadCN provides a CLI tool to streamline integration. Install it using the command:</p><pre>npx shadcn-ui init</pre><p>Follow the interactive CLI prompts to:</p><ol><li>Set the directory for components (e.g., components/ui).</li><li>Choose Tailwind CSS as the styling framework.</li><li>Include the base configuration and default themes.</li></ol><h3>Step 4: Add Components</h3><p>ShadCN allows you to add specific components as needed. For example, to add a <strong>Button</strong>, run:</p><pre>npx shadcn-ui add button</pre><p>This generates a button.tsx file in the components/ui directory.</p><h3>Step 5: Using ShadCN Components in Next.js</h3><p>Let’s integrate the ShadCN <strong>Button</strong> component into your Next.js app.</p><h3>Update the Button Component</h3><p>The default ShadCN button is customizable. You can update its styling and functionality in components/ui/button.tsx.</p><p>Example:</p><pre>import * as React from &#39;react&#39;;<br>import { cn } from &#39;@/utils/cn&#39;;<br><br>export interface ButtonProps extends React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt; {<br>  variant?: &#39;default&#39; | &#39;outline&#39; | &#39;ghost&#39;;<br>}<br><br>const Button = React.forwardRef&lt;HTMLButtonElement, ButtonProps&gt;(<br>  ({ className, variant = &#39;default&#39;, ...props }, ref) =&gt; {<br>    return (<br>      &lt;button<br>        ref={ref}<br>        className={cn(<br>          &#39;px-4 py-2 rounded font-medium transition&#39;,<br>          variant === &#39;outline&#39; &amp;&amp; &#39;border border-gray-300&#39;,<br>          variant === &#39;ghost&#39; &amp;&amp; &#39;bg-transparent text-gray-600&#39;,<br>          className<br>        )}<br>        {...props}<br>      /&gt;<br>    );<br>  }<br>);<br><br>Button.displayName = &#39;Button&#39;;<br>export default Button;</pre><h3>Using the Button</h3><p>Now, use the button in a page component like pages/index.tsx:</p><pre>import React from &#39;react&#39;;<br>import Button from &#39;@/components/ui/button&#39;;<br><br>export default function Home() {<br>  return (<br>    &lt;main className=&quot;flex flex-col items-center justify-center h-screen bg-gray-100&quot;&gt;<br>      &lt;h1 className=&quot;text-4xl font-bold mb-4&quot;&gt;Welcome to ShadCN in Next.js 14&lt;/h1&gt;<br>      &lt;Button variant=&quot;default&quot; className=&quot;bg-blue-600 text-white hover:bg-blue-700&quot;&gt;<br>        Click Me<br>      &lt;/Button&gt;<br>      &lt;Button variant=&quot;outline&quot; className=&quot;mt-4&quot;&gt;<br>        Outline Button<br>      &lt;/Button&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><h3>Step 6: Adding More Components</h3><p>You can add additional components like <strong>Card</strong>, <strong>Modal</strong>, or <strong>Dropdown</strong> by running similar commands.</p><pre>npx shadcn-ui add card<br>npx shadcn-ui add modal</pre><p>Customize them as needed and integrate them into your app.</p><h3>Step 7: Theming ShadCN Components</h3><p>ShadCN supports theming via Tailwind. To create a custom theme, update your tailwind.config.js:</p><pre>theme: {<br>  extend: {<br>    colors: {<br>      primary: &#39;#4F46E5&#39;, // Indigo<br>      secondary: &#39;#10B981&#39;, // Green<br>    },<br>  },<br>},</pre><p>Use these theme colors in your components:</p><pre>&lt;Button className=&quot;bg-primary text-white&quot;&gt;Primary Button&lt;/Button&gt;</pre><h3>Best Practices</h3><ol><li><strong>Keep Components Modular</strong>: Store reusable components in dedicated directories.</li><li><strong>Optimize for Accessibility</strong>: Use semantic HTML and ARIA attributes where necessary.</li><li><strong>Use Utilities Effectively</strong>: Leverage Tailwind’s utility classes for rapid styling.</li><li><strong>Test Responsiveness</strong>: Ensure components adapt to different screen sizes.</li></ol><h3>Conclusion</h3><p>Integrating ShadCN with Next.js 14 offers a powerful combination of prebuilt, accessible components and utility-first styling. By following the steps above, you can quickly set up and customize your project to deliver scalable, maintainable, and visually appealing web applications.</p><p>Have you tried ShadCN in your Next.js projects? Share your thoughts and experiences below! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917bb1946cba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/how-to-integrate-shadcn-into-next-js-14-a-step-by-step-guide-917bb1946cba">How to Integrate shadcn into Next.js 14: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Multi-Layer Context System for Complex React Apps]]></title>
            <link>https://medium.com/zestgeek/building-a-multi-layer-context-system-for-complex-react-apps-45daf0446601?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/45daf0446601</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 06:57:41 GMT</pubDate>
            <atom:updated>2024-11-20T06:54:43.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing state in complex React applications often requires a scalable and maintainable approach. While tools like Redux or Zustand are great for such use cases, React’s Context API, when used strategically, can also handle intricate state management needs. A multi-layer context system allows you to compartmentalize state logically, making your application more modular and efficient.</p><p>In this guide, we’ll explore how to build and use a multi-layer context system in React.</p><h3>Why a Multi-Layer Context System?</h3><p>A single React Context can become challenging to manage in large-scale applications, leading to:</p><ul><li><strong>Performance bottlenecks</strong>: Frequent re-renders caused by unrelated state changes.</li><li><strong>Reduced modularity</strong>: A single source of truth makes the code less reusable and harder to debug.</li><li><strong>Context bloat</strong>: Combining unrelated state into one context increases complexity.</li><li>A multi-layer context system solves these problems by dividing state into smaller, focused contexts, ensuring better performance and easier maintainability.</li></ul><h3>Designing a Multi-Layer Context System</h3><p>The key steps to building a multi-layer context system are:</p><ol><li><strong>Identify Logical Layers</strong>: Group your state into logical categories (e.g., Auth, UI, Data).</li><li><strong>Create Separate Contexts</strong>: Define a context for each layer.</li><li><strong>Combine Providers</strong>: Use a provider composition pattern to wrap your app.</li><li><strong>Access Contexts Modularly</strong>: Leverage useContext for layer-specific state.</li></ol><h3>Step 1: Identifying Layers</h3><p>For this example, let’s assume a scenario with three layers:</p><ul><li><strong>Auth Layer</strong>: Manages authentication state (e.g., user info, login status).</li><li><strong>UI Layer</strong>: Tracks UI state (e.g., theme, modals).</li><li><strong>Data Layer</strong>: Handles application data (e.g., fetched APIs, filters).</li></ul><h3>Step 2: Creating Contexts</h3><p>Here’s how to define contexts for each layer.</p><h4>Auth Context</h4><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>const AuthContext = createContext();<br><br>export const AuthProvider = ({ children }) =&gt; {<br>  const [user, setUser] = useState(null);<br><br>  const login = (userInfo) =&gt; setUser(userInfo);<br>  const logout = () =&gt; setUser(null);<br><br>  return (<br>    &lt;AuthContext.Provider value={{ user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>export default AuthContext;</pre><h4>UI Context</h4><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>const UIContext = createContext();<br><br>export const UIProvider = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br>  const [isModalOpen, setModalOpen] = useState(false);<br><br>  const toggleTheme = () =&gt; setTheme((prev) =&gt; (prev === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;));<br>  const toggleModal = () =&gt; setModalOpen((prev) =&gt; !prev);<br><br>  return (<br>    &lt;UIContext.Provider value={{ theme, isModalOpen, toggleTheme, toggleModal }}&gt;<br>      {children}<br>    &lt;/UIContext.Provider&gt;<br>  );<br>};<br><br>export default UIContext;</pre><h4>Data Context</h4><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>const DataContext = createContext();<br><br>export const DataProvider = ({ children }) =&gt; {<br>  const [data, setData] = useState([]);<br><br>  const updateData = (newData) =&gt; setData(newData);<br><br>  return (<br>    &lt;DataContext.Provider value={{ data, updateData }}&gt;<br>      {children}<br>    &lt;/DataContext.Provider&gt;<br>  );<br>};<br><br>export default DataContext;</pre><h3>Step 3: Combining Providers</h3><p>Use a provider composition function to wrap your app with all context providers.</p><pre>import React from &#39;react&#39;;<br>import { AuthProvider } from &#39;./contexts/AuthContext&#39;;<br>import { UIProvider } from &#39;./contexts/UIContext&#39;;<br>import { DataProvider } from &#39;./contexts/DataContext&#39;;<br><br>const AppProviders = ({ children }) =&gt; {<br>  return (<br>    &lt;AuthProvider&gt;<br>      &lt;UIProvider&gt;<br>        &lt;DataProvider&gt;{children}&lt;/DataProvider&gt;<br>      &lt;/UIProvider&gt;<br>    &lt;/AuthProvider&gt;<br>  );<br>};<br><br>export default AppProviders;</pre><p>Wrap your app in AppProviders in the index.js or _app.js file:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br>import AppProviders from &#39;./contexts/AppProviders&#39;;<br><br>ReactDOM.render(<br>  &lt;AppProviders&gt;<br>    &lt;App /&gt;<br>  &lt;/AppProviders&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><h3>Step 4: Accessing Contexts</h3><p>Now, components can access specific layers as needed.</p><h4>Example: Auth Layer</h4><pre>import React, { useContext } from &#39;react&#39;;<br>import AuthContext from &#39;../contexts/AuthContext&#39;;<br><br>const Profile = () =&gt; {<br>  const { user, login, logout } = useContext(AuthContext);<br><br>  return user ? (<br>    &lt;div&gt;<br>      &lt;p&gt;Welcome, {user.name}!&lt;/p&gt;<br>      &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>    &lt;/div&gt;<br>  ) : (<br>    &lt;button onClick={() =&gt; login({ name: &#39;John Doe&#39; })}&gt;Login&lt;/button&gt;<br>  );<br>};<br><br>export default Profile;</pre><h4>Example: UI Layer</h4><pre>import React, { useContext } from &#39;react&#39;;<br>import UIContext from &#39;../contexts/UIContext&#39;;<br><br>const Header = () =&gt; {<br>  const { theme, toggleTheme } = useContext(UIContext);<br><br>  return (<br>    &lt;header style={{ background: theme === &#39;light&#39; ? &#39;#fff&#39; : &#39;#333&#39;, color: theme === &#39;light&#39; ? &#39;#000&#39; : &#39;#fff&#39; }}&gt;<br>      &lt;h1&gt;My App&lt;/h1&gt;<br>      &lt;button onClick={toggleTheme}&gt;Switch to {theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;} mode&lt;/button&gt;<br>    &lt;/header&gt;<br>  );<br>};<br><br>export default Header;</pre><h3>Benefits of a Multi-Layer Context System</h3><ol><li><strong>Improved Performance</strong>: Updates in one layer don’t affect others, reducing unnecessary re-renders.</li><li><strong>Modularity</strong>: State is logically separated, making code more maintainable and scalable.</li><li><strong>Reusability</strong>: Contexts can be reused across different projects or modules.</li></ol><h3>Best Practices</h3><ul><li><strong>Avoid Over-Nesting:</strong> Limit the number of providers to maintain readability.</li><li><strong>Memoize Context Values:</strong> Use useMemo to prevent unnecessary updates.</li><li><strong>Monitor Performance:</strong> Use React DevTools to ensure layers don’t cause excessive re-renders.</li></ul><h3>Conclusion</h3><p>A multi-layer context system is a powerful and efficient way to manage state in complex React applications. By dividing concerns into separate contexts, you gain better performance, maintainability, and modularity. Start implementing this approach in your projects to simplify state management without compromising functionality!</p><p>Are you ready to scale your React apps with a multi-layer context system? Share your experiences and thoughts below! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45daf0446601" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/building-a-multi-layer-context-system-for-complex-react-apps-45daf0446601">Building a Multi-Layer Context System for Complex React Apps</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with useContext in Next.js: A State Management Primer]]></title>
            <link>https://medium.com/zestgeek/getting-started-with-usecontext-in-next-js-a-state-management-primer-ad858ae3d7d8?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad858ae3d7d8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 16:53:40 GMT</pubDate>
            <atom:updated>2024-11-18T16:53:21.616Z</atom:updated>
            <content:encoded><![CDATA[<p>State management is one of the most crucial aspects of building React applications, and when you’re developing with <strong>Next.js</strong>, it becomes even more important due to its server-side rendering (SSR) capabilities and complex app structure. While React provides several solutions for managing state, the useContext hook is an incredibly powerful and simple tool for sharing state across components without prop drilling. This article will guide you through getting started with useContext in Next.js, helping you understand the basics and apply them effectively.</p><h3>What is useContext?</h3><p>The useContext hook in React allows you to consume context values, making it easier to share state between components without needing to pass props down manually. In Next.js applications, this is especially useful for managing global state such as authentication, user settings, or theme preferences.</p><p>By combining useContext with <strong>React Context</strong>, you can create a global state system that is accessible throughout your component tree.</p><h3>Why Use useContext in Next.js?</h3><p>When working with Next.js, you often need a state management solution that can work well across both client-side and server-side rendering. While libraries like Redux or Zustand are popular, React’s native useContext combined with useState or useReducer provides a simple, yet effective solution for many use cases.</p><p>Here are a few reasons to use useContext in Next.js:</p><ul><li><strong>Global state management</strong>: Share state across components without prop drilling.</li><li><strong>Simplified solution</strong>: No need to install additional libraries for basic state management.</li><li><strong>Integration with SSR</strong>: Can easily be combined with Next.js’s server-side rendering, enabling state persistence across pages.</li></ul><h3>Setting Up useContext in Next.js: A Step-by-Step Guide</h3><p>Let’s dive into how to implement useContext in a Next.js application, from creating context to consuming it in components.</p><h4>1. Create a Context</h4><p>First, you need to create a context. The createContext function from React is used to initialize the context. It takes a default value as an argument, which is used when no provider is found in the component tree.</p><p>Let’s create a simple ThemeContext to manage the theme state:</p><pre>// context/ThemeContext.js<br>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>// Create context<br>const ThemeContext = createContext();<br><br>// Create a provider component<br>export const ThemeProvider = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState(&#39;light&#39;); // default theme<br><br>  // Toggle theme between &#39;light&#39; and &#39;dark&#39;<br>  const toggleTheme = () =&gt; {<br>    setTheme((prevTheme) =&gt; (prevTheme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;));<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};<br><br>// Custom hook to use the context<br>export const useTheme = () =&gt; useContext(ThemeContext);</pre><p>In the above code, we’ve created a ThemeContext and a ThemeProvider to manage the state. The useTheme custom hook will allow us to easily access the context value in our components.</p><h4>2. Wrap the Application with the Context Provider</h4><p>Now that you have your context and provider set up, the next step is to wrap your application with the provider in the _app.js file. This ensures that the context is available throughout the entire component tree.</p><pre>// pages/_app.js<br>import React from &#39;react&#39;;<br>import { ThemeProvider } from &#39;../context/ThemeContext&#39;;<br><br>const MyApp = ({ Component, pageProps }) =&gt; {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>};<br><br>export default MyApp;</pre><p>By wrapping the component tree in ThemeProvider, you ensure that any component in your app can access the theme and toggleTheme values.</p><h4>3. Consume Context in Components</h4><p>Now, you can use the useTheme hook to access and update the theme in any component. Let’s create a simple Header component that displays the current theme and allows users to toggle it.</p><pre>// components/Header.js<br>import React from &#39;react&#39;;<br>import { useTheme } from &#39;../context/ThemeContext&#39;;<br><br>const Header = () =&gt; {<br>  const { theme, toggleTheme } = useTheme();<br><br>  return (<br>    &lt;header style={{ backgroundColor: theme === &#39;light&#39; ? &#39;#fff&#39; : &#39;#333&#39;, color: theme === &#39;light&#39; ? &#39;#000&#39; : &#39;#fff&#39; }}&gt;<br>      &lt;h1&gt;Current Theme: {theme}&lt;/h1&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/header&gt;<br>  );<br>};<br><br>export default Header;</pre><p>In this example, the Header component consumes the theme value and the toggleTheme function. When the user clicks the button, it switches between light and dark themes.</p><h4>4. Using useContext in Server-Side Rendering (SSR)</h4><p>Since Next.js supports SSR, it’s important to handle context in a way that works with both client-side and server-side rendering. Fortunately, useContext integrates smoothly with Next.js&#39;s SSR model.</p><p>However, you should be aware that on the initial render, the context might be empty or have a default value. To handle this, you can use Next.js’s getServerSideProps or getStaticProps to pre-load data if necessary.</p><p>For instance, you can fetch the user’s preferred theme from a database or API and set it in your context before rendering:</p><pre>// pages/index.js<br>import React, { useEffect } from &#39;react&#39;;<br>import { useTheme } from &#39;../context/ThemeContext&#39;;<br><br>const HomePage = () =&gt; {<br>  const { theme, toggleTheme } = useTheme();<br><br>  // UseEffect to load dynamic data (e.g., user preferences)<br>  useEffect(() =&gt; {<br>    // You can fetch and set the theme here if needed<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to the {theme === &#39;light&#39; ? &#39;Light&#39; : &#39;Dark&#39;} Side!&lt;/h1&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;</pre><p>In this case, getServerSideProps or getStaticProps could be used to fetch data on the server side and pass it into the ThemeProvider on initial render.</p><h3>Best Practices for useContext in Next.js</h3><ol><li><strong>Avoid Overusing Context</strong>: While useContext is powerful, using it for everything can lead to performance issues. For complex state management, consider using solutions like Redux or Zustand.</li><li><strong>Split Contexts by Domain</strong>: Rather than creating one large context for everything, break it into smaller, domain-specific contexts (e.g., theme, authentication, user preferences).</li><li><strong>Use Memoization</strong>: Use useMemo to optimize the performance of context values that are expensive to compute or update frequently.</li><li><strong>Leverage Server-Side Rendering (SSR)</strong>: Next.js’s SSR capabilities can be utilized to pre-load data and provide an optimal user experience right from the first render.</li></ol><h3>Conclusion</h3><p>useContext is a powerful tool for managing global state in your Next.js app. By following this guide, you can effectively manage shared state like themes, authentication, and user preferences without prop drilling. While it’s a great solution for many scenarios, remember that performance can degrade if overused. Always consider splitting your contexts, memoizing values, and exploring other state management solutions for more complex use cases.</p><p>With these techniques, you’re ready to get started with useContext in Next.js and optimize your app’s state management system! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad858ae3d7d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/getting-started-with-usecontext-in-next-js-a-state-management-primer-ad858ae3d7d8">Getting Started with useContext in Next.js: A State Management Primer</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization Techniques with React’s useContext]]></title>
            <link>https://medium.com/zestgeek/performance-optimization-techniques-with-reacts-usecontext-5dc7e4ef6b25?source=rss----16e54d2de185---4</link>
            <guid isPermaLink="false">https://medium.com/p/5dc7e4ef6b25</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Love Trivedi]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 10:37:20 GMT</pubDate>
            <atom:updated>2024-11-14T10:26:43.919Z</atom:updated>
            <content:encoded><![CDATA[<p>The useContext hook is a powerful tool in React for managing global state. While convenient, useContext can sometimes lead to performance issues, especially in applications with complex or deeply nested component trees. In this article, we’ll explore some techniques to optimize useContext for better performance, helping you make the most of this essential hook without compromising your app’s speed.</p><h3>Why useContext Can Impact Performance</h3><p>React’s useContext hook provides shared state to components, but it can also trigger re-renders across every component that consumes it whenever the context changes. This can become problematic in applications with deeply nested or heavily dependent components, as unnecessary re-renders may lead to sluggish performance.</p><h3>Optimization Techniques</h3><p>Here are some practical techniques to help optimize useContext and prevent unwanted re-renders.</p><h4>1. Split Contexts for Different States</h4><p>One of the simplest ways to optimize useContext is to split your contexts based on the data they hold. Instead of using one large context, break it into smaller contexts for specific pieces of state. This approach limits re-renders to only the parts of the app that consume the relevant context.</p><p>For example, let’s say we have a theme and a user authentication state:</p><pre>// ThemeContext.js<br>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>const ThemeContext = createContext();<br>export const ThemeProvider = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};<br><br>export const useTheme = () =&gt; useContext(ThemeContext);<br><br>// AuthContext.js<br>const AuthContext = createContext();<br>export const AuthProvider = ({ children }) =&gt; {<br>  const [user, setUser] = useState(null);<br>  return (<br>    &lt;AuthContext.Provider value={{ user, setUser }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>export const useAuth = () =&gt; useContext(AuthContext);</pre><p>This way, theme-related updates only affect components consuming the ThemeContext, while user-related updates only impact components using AuthContext.</p><h4>2. Use Memoization with Context Values</h4><p>Whenever context values are updated, all components using that context re-render. Wrapping context values in useMemo can prevent unnecessary re-renders by memoizing the value, especially if it’s derived from other states or calculated on each render.</p><pre>import React, { createContext, useState, useMemo, useContext } from &#39;react&#39;;<br><br>const DataContext = createContext();<br><br>export const DataProvider = ({ children }) =&gt; {<br>  const [data, setData] = useState({ name: &#39;John Doe&#39;, age: 30 });<br><br>  const value = useMemo(() =&gt; ({ data, setData }), [data]);<br><br>  return (<br>    &lt;DataContext.Provider value={value}&gt;<br>      {children}<br>    &lt;/DataContext.Provider&gt;<br>  );<br>};<br><br>export const useData = () =&gt; useContext(DataContext);</pre><p>In this example, the value object containing data and setData is only recalculated when data changes, reducing unnecessary renders.</p><h4>3. Avoid Passing Functions Directly as Context Values</h4><p>Passing functions directly to context providers, especially if they contain dependencies, can cause re-renders whenever they are redefined. Use useCallback to ensure functions are only redefined when necessary.</p><pre>import React, { createContext, useState, useCallback, useContext } from &#39;react&#39;;<br><br>const CounterContext = createContext();<br><br>export const CounterProvider = ({ children }) =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const increment = useCallback(() =&gt; setCount(prev =&gt; prev + 1), []);<br>  const decrement = useCallback(() =&gt; setCount(prev =&gt; prev - 1), []);<br><br>  return (<br>    &lt;CounterContext.Provider value={{ count, increment, decrement }}&gt;<br>      {children}<br>    &lt;/CounterContext.Provider&gt;<br>  );<br>};<br><br>export const useCounter = () =&gt; useContext(CounterContext);</pre><p>y memoizing increment and decrement with useCallback, we prevent unnecessary re-renders in components consuming this context.</p><h4>4. Use Context Selectors</h4><p>If you’re dealing with large objects in your context, consider using context selectors to only subscribe to specific parts of the context. While React’s core library doesn’t natively support context selectors, libraries like use-context-selector can help.</p><p>Here’s an example using use-context-selector:</p><pre>import { createContext, useContextSelector } from &#39;use-context-selector&#39;;<br>import React, { useState } from &#39;react&#39;;<br><br>const AppContext = createContext();<br><br>export const AppProvider = ({ children }) =&gt; {<br>  const [user, setUser] = useState({ name: &#39;Alice&#39;, age: 28 });<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br><br>  return (<br>    &lt;AppContext.Provider value={{ user, setUser, theme, setTheme }}&gt;<br>      {children}<br>    &lt;/AppContext.Provider&gt;<br>  );<br>};<br><br>export const useUser = () =&gt; useContextSelector(AppContext, ctx =&gt; ctx.user);<br>export const useTheme = () =&gt; useContextSelector(AppContext, ctx =&gt; ctx.theme);</pre><p>With use-context-selector, you can create isolated subscriptions to specific parts of the context, reducing re-renders for other unrelated values.</p><h4>5. Implement React.memo on Context Consumers</h4><p>If you’re using functional components that don’t need to re-render when the context changes, wrap them in React.memo to prevent unnecessary re-renders. This is particularly useful when components receive the context as props but don’t actually use it in a way that requires frequent updates.</p><pre>import React, { memo } from &#39;react&#39;;<br>import { useTheme } from &#39;./ThemeContext&#39;;<br><br>const Header = memo(() =&gt; {<br>  const { theme } = useTheme();<br><br>  return &lt;header style={{ background: theme === &#39;dark&#39; ? &#39;#333&#39; : &#39;#fff&#39; }}&gt;Header&lt;/header&gt;;<br>});<br><br>export default Header;</pre><p>Using memo here ensures that Header only re-renders when the theme context changes, reducing redundant re-renders.</p><h4>6. Use Local State for Non-Global Data</h4><p>Not every piece of state needs to live in a context. For example, temporary states like form inputs or modal visibility can be managed with local component state. By keeping such state local, you avoid the performance cost of updating context providers.</p><pre>const Modal = () =&gt; {<br>  const [isOpen, setIsOpen] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true)}&gt;Open Modal&lt;/button&gt;<br>      {isOpen &amp;&amp; &lt;div&gt;Modal Content&lt;/div&gt;}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this example, isOpen doesn’t need to be in the global context, which keeps your app more performant and modular.</p><h3>Conclusion</h3><p>While useContext is a powerful tool for managing global state, it’s important to be mindful of its performance implications, especially in larger applications. By using techniques such as splitting contexts, memoizing values, avoiding inline functions, using context selectors, and leveraging local state, you can ensure that your app remains efficient and responsive.</p><p>With these optimizations, useContext can be a highly effective, lightweight solution for managing state, even in complex React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc7e4ef6b25" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zestgeek/performance-optimization-techniques-with-reacts-usecontext-5dc7e4ef6b25">Performance Optimization Techniques with React’s useContext</a> was originally published in <a href="https://medium.com/zestgeek">ZestGeek</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>