<?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 Bhavyasavaliya on Medium]]></title>
        <description><![CDATA[Stories by Bhavyasavaliya on Medium]]></description>
        <link>https://medium.com/@bhavyasavaliya.bs?source=rss-7a0b86c92fe1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TA7-auT1F-GeqFUC</url>
            <title>Stories by Bhavyasavaliya on Medium</title>
            <link>https://medium.com/@bhavyasavaliya.bs?source=rss-7a0b86c92fe1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:44:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhavyasavaliya.bs/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[Agentic Engineering: A Practical Guide to Building Software with AI Agents]]></title>
            <link>https://medium.com/@bhavyasavaliya.bs/agentic-engineering-a-practical-guide-to-building-software-with-ai-agents-9f7b19cdb5e1?source=rss-7a0b86c92fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7b19cdb5e1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bhavyasavaliya]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 19:33:01 GMT</pubDate>
            <atom:updated>2026-08-11T19:33:01.406Z</atom:updated>
            <content:encoded><![CDATA[<p>AI isn’t just generating code anymore.</p><p>A few years ago, AI coding tools were mainly used for:</p><ul><li>Code completion</li><li>Generating functions</li><li>Explaining errors</li><li>Writing small snippets</li></ul><p>Today, AI coding agents can explore a repository, understand existing patterns, modify multiple files, run tests, investigate failures, and iterate toward a goal.</p><p>That’s a bigger shift than simply <strong>AI writing code</strong>.</p><p>We’re moving toward:</p><blockquote><strong><em>Developer defines the goal, context, constraints, and success criteria — while the AI agent handles more of the implementation and iteration.</em></strong></blockquote><p>This is the idea behind <strong>Agentic Engineering</strong>.</p><p>The terminology is still evolving. You may also hear <em>agentic coding</em>, <em>agentic software development</em>, or <em>AI coding agents</em>. The common idea is that AI is becoming capable of participating in multi-step engineering work.</p><h3>What Is an AI Agent?</h3><p>A simple definition:</p><blockquote><strong><em>An AI agent is an AI system that works toward a goal by using tools, taking actions, observing results, and adapting its approach.</em></strong></blockquote><p>A traditional chatbot looks like:</p><pre>Question → Answer</pre><p>An engineering agent looks more like:</p><pre>Goal<br> ↓<br>Explore<br> ↓<br>Plan<br> ↓<br>Act<br> ↓<br>Observe<br> ↓<br>Adapt<br> ↓<br>Repeat</pre><p>For example, an agent can:</p><ol><li>Understand a feature request</li><li>Explore the repository</li><li>Find relevant files</li><li>Create a plan</li><li>Modify the code</li><li>Run tests</li><li>Investigate failures</li><li>Fix problems</li><li>Review the result</li></ol><p>That’s very different from simply asking:</p><blockquote><em>“Write this function for me.”</em></blockquote><h3>The Agentic Engineering Workflow</h3><p>A useful mental model is:</p><pre>Goal<br> ↓<br>Scope<br> ↓<br>Design<br> ↓<br>Specs<br> ↓<br>Context<br> ↓<br>Plan<br> ↓<br>Guardrails<br> ↓<br>Agent + Tools<br> ↓<br>Verification<br> ↓<br>Code Review<br> ↓<br>Testing</pre><p>Let’s understand this with a React Native example.</p><p>Imagine the requirement:</p><blockquote><strong><em>“Add offline support for editing a user’s profile.”</em></strong></blockquote><h3>1. Scope — What Are We Building?</h3><p>Scope defines the boundaries.</p><h3>In scope</h3><ul><li>Profile editing</li><li>Local persistence</li><li>Network detection</li><li>Synchronization when online</li></ul><h3>Out of scope</h3><ul><li>Authentication changes</li><li>Backend API changes</li><li>Navigation redesign</li><li>Unrelated UI changes</li></ul><p>So:</p><blockquote><strong><em>Add offline profile editing while keeping the existing API and UI architecture.</em></strong></blockquote><p><strong>Scope = What are we changing?</strong></p><h3>2. Design — How Should It Work?</h3><p>A possible flow:</p><pre>User edits profile<br>       ↓<br>Save locally<br>       ↓<br>   Online?<br>  ↓       ↓<br> Yes      No<br>  ↓       ↓<br>Sync    Keep pending<br>  ↓       ↓<br>API     Internet returns<br>          ↓<br>         Sync</pre><p>The design should answer questions like:</p><ul><li>Where is profile state stored?</li><li>What storage already exists?</li><li>How is connectivity detected?</li><li>How are pending changes tracked?</li><li>What happens when synchronization fails?</li></ul><p><strong>Design = How should the system work?</strong></p><h3>3. Specs — What Exactly Must Happen?</h3><p>A specification makes the requirement testable.</p><p>For example:</p><ul><li>Users can edit their profile offline.</li><li>Changes are stored locally.</li><li>Pending changes survive app restart.</li><li>Changes synchronize when connectivity returns.</li><li>Failed synchronization doesn’t lose data.</li><li>Duplicate synchronization is avoided.</li><li>Existing online behavior continues to work.</li></ul><p>Now we have something the agent can implement <strong>and something we can verify</strong>.</p><p><strong>Specs = Exact rules and expected behavior.</strong></p><h3>4. Context — What Does the Agent Need to Know?</h3><p>Don’t give the agent only:</p><blockquote><em>“Add offline profile editing.”</em></blockquote><p>Give it relevant project context:</p><pre>Profile screen<br>API service<br>State management<br>Storage utilities<br>Network utilities<br>Existing tests<br>Project conventions</pre><p>The important word is <strong>relevant</strong>.</p><p>More context doesn’t always mean better context. Giving an agent hundreds of unrelated files can make the task harder.</p><p><strong>Context = What does the agent need to know?</strong></p><h3>5. Planning and Task Decomposition</h3><p>Break the feature into understandable steps:</p><pre>Understand profile architecture<br>          ↓<br>Find API and state management<br>          ↓<br>Understand storage<br>          ↓<br>Implement persistence<br>          ↓<br>Implement synchronization<br>          ↓<br>Handle failures<br>          ↓<br>Add tests</pre><p>The plan can also change.</p><p>For example, the agent may discover that the project already has an offline storage service. It can then reuse it instead of creating another one.</p><p><strong>Planning = Decide how to execute the work.</strong></p><h3>6. Tools and the Agent Loop</h3><p>An agent needs tools to actually work.</p><p>Typical tools include:</p><ul><li>File search</li><li>File editing</li><li>Terminal</li><li>Tests</li><li>Git</li><li>Build tools</li></ul><p>The agent can then work through a loop:</p><pre>Plan<br> ↓<br>Act<br> ↓<br>Run tests<br> ↓<br>Observe failure<br> ↓<br>Investigate<br> ↓<br>Fix<br> ↓<br>Test again</pre><p>For example:</p><pre>15 tests passed<br>2 tests failed<br>       ↓<br>Investigate<br>       ↓<br>Fix implementation<br>       ↓<br>17 tests passed</pre><p>This iterative behavior is one of the biggest differences between an AI code generator and an AI coding agent.</p><p><strong>Agent Loop = Plan → Act → Observe → Adapt</strong></p><h3>7. Guardrails — What Can the Agent Do?</h3><p>Agents need boundaries.</p><p>For our feature:</p><h3>Allowed</h3><pre>✓ Modify profile-related code<br>✓ Add synchronization<br>✓ Add tests<br>✓ Reuse existing utilities</pre><h3>Not allowed</h3><pre>✗ Change authentication<br>✗ Change backend APIs<br>✗ Modify unrelated screens<br>✗ Remove existing tests<br>✗ Change production configuration</pre><p>Guardrails can come from instructions, permissions, tool restrictions, validation, or human approval.</p><blockquote><strong><em>Give the agent enough freedom to be useful, but not unlimited freedom to cause damage.</em></strong></blockquote><h3>8. Verification and Code Review</h3><p>An agent saying:</p><blockquote><em>“Done.”</em></blockquote><p>doesn’t mean the task is complete.</p><p>We need evidence.</p><p>For example:</p><pre>✓ Online editing works<br>✓ Offline editing works<br>✓ Changes persist<br>✓ App restart works<br>✓ Reconnection sync works<br>✓ Failed sync preserves data<br>✓ Duplicate sync is prevented</pre><p>Then review the diff:</p><pre>git diff</pre><p>Ask:</p><ul><li>Did it modify the right files?</li><li>Did it change unrelated code?</li><li>Did it introduce unnecessary dependencies?</li><li>Does it follow the existing architecture?</li><li>Did it actually solve the requirement?</li></ul><p>Tests tell us whether certain behaviors work.</p><p><strong>Code review tells us whether the implementation makes sense.</strong></p><h3>What Can Go Wrong?</h3><p>Agentic development isn’t magic.</p><p>Common problems include:</p><h3>Wrong context</h3><p>The agent misunderstands the existing architecture.</p><h3>Over-scoping</h3><p>The agent changes unrelated files.</p><h3>Dependency creep</h3><p>It adds a new library when an existing utility could be reused.</p><h3>False confidence</h3><p>The agent reports success without testing important scenarios.</p><h3>Architectural drift</h3><p>The feature works but makes the codebase harder to maintain.</p><p>This is why good agentic development requires more than good prompts.</p><p>It requires <strong>good engineering judgment</strong>.</p><h3>When Should You Use an Agent?</h3><p>Agents are especially useful for:</p><ul><li>Repository exploration</li><li>Large refactors</li><li>Repetitive code changes</li><li>Test generation</li><li>Debugging</li><li>Multi-file features</li><li>Migrations</li></ul><p>Be more careful with:</p><ul><li>Production deployments</li><li>Security-critical changes</li><li>Authentication</li><li>Payment systems</li><li>Destructive operations</li><li>Sensitive data</li></ul><p>A simple principle:</p><blockquote><strong><em>The higher the risk, the stronger the human oversight should be.</em></strong></blockquote><h3>What Changes for Developers?</h3><p>Agentic Engineering doesn’t mean:</p><blockquote><em>“AI does everything.”</em></blockquote><p>The developer still owns:</p><ul><li>Problem definition</li><li>Architecture</li><li>Requirements</li><li>Context</li><li>Constraints</li><li>Code review</li><li>Testing</li><li>Final decisions</li></ul><p>The agent can take on more of:</p><ul><li>Repository exploration</li><li>Implementation</li><li>Repetitive coding</li><li>Test execution</li><li>Debugging</li><li>Iteration</li></ul><p>So the shift isn’t:</p><blockquote><strong><em>Developer → AI</em></strong></blockquote><p>It’s:</p><blockquote><strong><em>Developer + AI → More capable engineering workflow</em></strong></blockquote><h3>The Mental Model</h3><p>You don’t need to memorize every AI term.</p><p>Remember:</p><pre>| **Concept**      | **Question**                      |<br>| ---------------- | --------------------------------- |<br>| **Scope**        | What are we building?             |<br>| **Design**       | How should it work?               |<br>| **Specs**        | What exactly must happen?         |<br>| **Context**      | What does the agent need to know? |<br>| **Tools**        | What can the agent use?           |<br>| **Guardrails**   | What is it allowed to do?         |<br>| **Agent Loop**   | How does it adapt?                |<br>| **Verification** | Did it achieve the goal?          |<br>| **Code Review**  | Did it make the right changes?    |<br>| **Testing**      | Does it work reliably?            |</pre><p>Or simply:</p><pre>Define<br> ↓<br>Constrain<br> ↓<br>Delegate<br> ↓<br>Observe<br> ↓<br>Verify<br> ↓<br>Review</pre><h3>Final Thought</h3><p>The biggest change isn’t that <strong>AI can write code</strong>.</p><p>AI has been generating code for a while.</p><p>The bigger change is that AI can increasingly participate in the <strong>engineering process</strong>:</p><blockquote><strong><em>Understand → Explore → Plan → Implement → Test → Adapt</em></strong></blockquote><p>That changes the developer’s role.</p><p>We need to become better at <strong>defining problems, designing systems, providing context, setting constraints, reviewing changes, and verifying software</strong>.</p><p>Agentic Engineering isn’t about removing developers from the loop.</p><p>It’s about giving developers a more capable collaborator.</p><blockquote><strong><em>The goal isn’t to make developers less important.</em></strong></blockquote><blockquote><strong><em>The goal is to make developers more effective.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7b19cdb5e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Offline-First Architecture in React Native: Building Apps That Work Without Internet]]></title>
            <link>https://medium.com/@bhavyasavaliya.bs/offline-first-architecture-in-react-native-building-apps-that-work-without-internet-d9e024fb2939?source=rss-7a0b86c92fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e024fb2939</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Bhavyasavaliya]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 20:37:26 GMT</pubDate>
            <atom:updated>2026-08-06T20:37:26.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Most mobile apps assume users always have a stable internet connection. In reality, that’s rarely true.</p><p>Users work from construction sites, warehouses, remote villages, underground parking, trains, airports, and places where the network is slow or unavailable.</p><p>If your app simply displays <strong>“No Internet Connection”</strong> and blocks the user, you’ve created a poor user experience.</p><p>Instead, modern mobile apps follow an <strong>Offline-First Architecture</strong>.</p><h3>What is Offline-First?</h3><p>Offline-first means your application continues to work even when the internet is unavailable.</p><p>Rather than depending on an API for every action, the app stores data locally and synchronizes it with the server when connectivity is restored.</p><pre>User Action<br>      │<br>      ▼<br>Save Locally<br>      │<br>      ▼<br>Continue Using App<br>      │<br>      ▼<br>Internet Returns<br>      │<br>      ▼<br>Auto Sync<br>      │<br>      ▼<br>Server Updated</pre><p>The goal is simple:</p><p><strong>Never let poor connectivity stop the user from doing their work.</strong></p><h3>Step 1: Detect Connectivity Efficiently</h3><p>A common mistake is checking the internet every second using setInterval().</p><pre>// ❌ Avoid this<br>setInterval(() =&gt; {<br>   checkInternet();<br>}, 1000);</pre><p>This wastes CPU resources and drains the device battery.</p><p>A better approach is using <strong>@react-native-community/netinfo</strong>, which listens for native operating system connectivity events.</p><pre>const netInfo = useNetInfo();</pre><pre>useEffect(() =&gt; {<br>   if (netInfo.isConnected &amp;&amp; netInfo.isInternetReachable) {<br>      syncPendingData();<br>   }<br>}, [netInfo.isConnected, netInfo.isInternetReachable]);</pre><p>Instead of polling continuously, the operating system notifies your app only when the network status changes.</p><h3>Step 2: Store User Actions Locally</h3><p>When the device is offline, don’t reject user actions.</p><p>Instead, save them locally.</p><p>Depending on your application’s complexity, you can use:</p><ul><li>AsyncStorage</li><li>SQLite</li><li>MMKV</li><li>Realm</li><li>WatermelonDB</li></ul><p>Small applications may work well with AsyncStorage, while larger offline-first systems often use a local database.</p><h3>Step 3: Build a Sync Queue</h3><p>Instead of immediately calling the API, push every offline action into a queue.</p><pre>User submits form<br>        │<br>        ▼<br>Pending Queue<br>        │<br>        ▼<br>Waiting...</pre><p>When the internet returns:</p><pre>Connectivity Restored<br>        │<br>        ▼<br>Read Queue<br>        │<br>        ▼<br>Upload Item 1<br>Upload Item 2<br>Upload Item 3<br>...<br>Queue Empty</pre><p>This ensures no user data is lost.</p><h3>Step 4: Retry Failed Uploads</h3><p>Production applications don’t stop after one failed request.</p><p>A sync engine usually follows this pattern:</p><pre>Upload Item<br>      │<br>      ▼<br>Success?</pre><pre>YES ─────────► Remove From Queue</pre><pre>NO<br> │<br> ▼<br>Retry Later</pre><p>This makes synchronization much more reliable in unstable network conditions.</p><h3>Step 5: Think About Conflict Resolution</h3><p>What happens if two devices update the same record while offline?</p><p>This is known as a <strong>conflict</strong>.</p><p>Common strategies include:</p><ul><li>Last Write Wins</li><li>Server Wins</li><li>Version Numbers</li><li>Manual Merge</li></ul><p>Choosing the right strategy depends on your business requirements.</p><h3>Step 6: Provide a Great User Experience</h3><p>Users shouldn’t feel like they’re offline.</p><p>Good offline experiences include:</p><ul><li>Forms continue working</li><li>Photos are saved locally</li><li>Pending items are clearly indicated</li><li>Automatic synchronization when connectivity returns</li><li>Success status after synchronization</li></ul><p>The user keeps working while the app handles synchronization in the background.</p><h3>Benefits of Offline-First</h3><p>✅ Better user experience</p><p>✅ No data loss</p><p>✅ Faster perceived performance</p><p>✅ Reliable in poor network conditions</p><p>✅ Reduced user frustration</p><p>✅ Production-ready architecture</p><h3>Final Thoughts</h3><p>Offline-first isn’t just about storing data locally.</p><p>It’s about designing an application that respects the user’s time and keeps them productive regardless of network quality.</p><p>Whether you’re building logistics, healthcare, field service, warehouse management, inspection, agriculture, or enterprise applications, an offline-first architecture can significantly improve reliability and user satisfaction.</p><p>The best mobile apps aren’t the ones that work only with fast internet — they’re the ones users can trust even when the network disappears.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e024fb2939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization in React: Real-World Examples]]></title>
            <link>https://medium.com/@bhavyasavaliya.bs/performance-optimization-in-react-real-world-examples-fcdb280a45ab?source=rss-7a0b86c92fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcdb280a45ab</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[perfomance]]></category>
            <category><![CDATA[improvement]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Bhavyasavaliya]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 05:48:32 GMT</pubDate>
            <atom:updated>2025-06-18T05:48:32.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>React is powerful, but it can suffer performance issues when components re-render unnecessarily or handle more work than needed.</p><p>This guide explores 6 common performance bottlenecks in real-world applications — along with practical techniques to address them. Each example includes before-and-after code and clear explanations of what’s happening, why it matters, and how to optimize it effectively.</p><h3><strong>1. Unnecessary Re-renders in Child Components</strong></h3><p>Consider a simple Counter component that displays a number. Even if only the input field is updated, the Counter still re-renders — a common inefficiency in many apps.</p><p><strong>Before Optimization</strong></p><pre>function Counter({ count }) {<br>  console.log(&quot;Counter rendered&quot;);<br>  return &lt;h2&gt;Count: {count}&lt;/h2&gt;;<br>}<br><br>function App() {<br>  const [count, setCount] = React.useState(0);<br>  const [text, setText] = React.useState(&quot;&quot;);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Counter count={count} /&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;input value={text} onChange={(e) =&gt; setText(e.target.value)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>After Optimization</strong></p><pre>const Counter = React.memo(function Counter({ count }) {<br>  console.log(&#39;Counter rendered&#39;);<br>  return &lt;h2&gt;Count: {count}&lt;/h2&gt;;<br>});</pre><p><strong>What’s happening?<br></strong>Every time the App component re-renders - even when updating the text input — the Counter component also re-renders.<br><strong>Why it&#39;s a problem?<br></strong>React re-renders all child components by default, even if their props haven’t changed. This adds up fast in large trees.<br><strong>Optimization Approach<br></strong>Use React.memo to prevent unnecessary re-renders by memoizing the component unless its props actually change.</p><h3>2. Rendering Huge Lists Without Virtualization</h3><p>Rendering thousands of DOM nodes can completely freeze your browser. If you ever render a long list — this is critical.</p><p><strong>Before Optimization</strong></p><pre>function App() {<br>  const items = Array.from({ length: 10000 }, (_, i) =&gt; `Item ${i}`);<br><br>  return (<br>    &lt;div style={{ height: &#39;400px&#39;, overflowY: &#39;auto&#39; }}&gt;<br>      {items.map((item) =&gt; (<br>        &lt;div key={item}&gt;{item}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>After Optimization (using </strong><strong>react-window)</strong></p><pre>import { FixedSizeList as List } from &#39;react-window&#39;;<br><br>function App() {<br>  const items = Array.from({ length: 10000 }, (_, i) =&gt; `Item ${i}`);<br><br>  return (<br>    &lt;List<br>      height={400}<br>      itemCount={items.length}<br>      itemSize={35}<br>      width={&#39;100%&#39;}<br>    &gt;<br>      {({ index, style }) =&gt; (<br>        &lt;div style={style}&gt;{items[index]}&lt;/div&gt;<br>      )}<br>    &lt;/List&gt;<br>  );<br>}</pre><p><strong>What’s happening?<br></strong>All 10,000 list items are rendered and pushed into the DOM at once.<br><strong>Why it&#39;s a problem?<br></strong>Rendering thousands of DOM nodes is memory-intensive and causes the browser to lag or freeze.<br><strong>Optimization Approach<br></strong>Use virtualization (react-window) to render only visible items and reuse DOM nodes during scroll. Smooth performance, minimal overhead.</p><h3>3. Function Re-created on Every Render</h3><p>Every render creates a new function instance (e.g., the onClick handler in a button). This can cause unnecessary re-renders of child components, especially when they are memorized.</p><p><strong>Before Optimization</strong></p><pre>function App() {<br>  const [count, setCount] = React.useState(0);<br>  return &lt;Button onClick={() =&gt; setCount(count + 1)} /&gt;;<br>}</pre><p><strong>After Optimization</strong></p><pre>const handleClick = React.useCallback(() =&gt; {<br>  setCount((prev) =&gt; prev + 1);<br>}, []);<br>return &lt;Button onClick={handleClick} /&gt;;</pre><p><strong>What’s happening?<br></strong>The inline arrow function gets recreated every time the component re-renders, so it has a new reference each time.<br><strong>Why it&#39;s a problem?<br></strong>If the Button component is memoized, it will still re-render because the onClick prop changes by reference.<br><strong>Optimization Approach<br></strong>Wrap the function in useCallback to keep the reference stable across renders and avoid unnecessary updates downstream.</p><h3>4. Tab Content Re-renders on Every Switch</h3><p>Switching between tabs causes all tab content to unmount and remount, losing state and triggering unnecessary re-renders.</p><p><strong>Before Optimization</strong></p><pre>{activeTab === &#39;profile&#39; &amp;&amp; &lt;Profile /&gt;}<br>{activeTab === &#39;settings&#39; &amp;&amp; &lt;Settings /&gt;}</pre><p><strong>After Optimization</strong></p><pre>const tabs = useMemo(() =&gt; ({<br>  profile: &lt;Profile /&gt;,<br>  settings: &lt;Settings /&gt;,<br>}), []);<br>return tabs[activeTab];</pre><p><strong>What’s happening?<br></strong>Each tab component mounts/unmounts when switching, resetting its internal state and triggering re-renders.<br><strong>Why it&#39;s a problem?<br></strong>Components lose their internal state, and there’s a noticeable delay on tab switches due to remounting.<br><strong>Optimization Approach<br></strong>Store components in useMemo and toggle visibility instead of remounting. This keeps the component’s state and makes switching faster.</p><h3>5. Uncontrolled Component Switching to Controlled</h3><p>Switching an input from uncontrolled to controlled (e.g., setting its value from undefined to a real value) leads to a React warning and a forced re-render.</p><p><strong>Before Optimization</strong></p><pre>function Input({ value }) {<br>  return &lt;input value={value} onChange={() =&gt; {}} /&gt;;<br>}</pre><p>When value is initially undefined, this becomes <strong>uncontrolled</strong>, and when it gets a value, React throws a warning and forces a re-render</p><p><strong>After Optimization</strong></p><pre>function Input({ value }) {<br>  return &lt;input value={value ?? &#39;&#39;} onChange={() =&gt; {}} /&gt;;<br>}</pre><p><strong>What’s happening?</strong><br>If value starts as undefined, React treats the input as uncontrolled. When it gets a value later, it switches to controlled — and React throws a warning.<br><strong>Why it&#39;s a problem?</strong><br>Switching from an uncontrolled to a controlled input in React causes the field to reset and displays a warning.<br><strong>How to fix it?</strong><br>Use a fallback value (value ?? &#39;&#39;) to keep the input controlled from the beginning, avoiding warning and preserving expected behavior.</p><h3>6. Large Components Doing Too Much</h3><p>Rendering too many components at once in a large bundle can delay the first paint, making your app feel slow and unresponsive.</p><p><strong>Before Optimization</strong></p><pre>function Dashboard() {<br>  return (<br>    &lt;&gt;<br>      &lt;HeavyChart /&gt;<br>      &lt;LiveFeed /&gt;<br>      &lt;WeatherWidget /&gt;<br>      &lt;NotificationPanel /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>All components are rendered and mounted at once.</p><p><strong>After Optimization (Code Splitting)</strong></p><pre>const HeavyChart = React.lazy(() =&gt; import(&#39;./HeavyChart&#39;));<br><br>function Dashboard() {<br>  return (<br>    &lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>      &lt;HeavyChart /&gt;<br>      {/* Other components can load similarly */}<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p><strong>What’s happening?<br></strong>All dashboard components are loaded upfront, even if they’re not visible or immediately needed.<br><strong>Why it&#39;s a problem?<br></strong>It bloats the initial JavaScript bundle, slowing down your app’s first render and hurting metrics like LCP.<br><strong>Optimization Approach<br></strong>Use React.lazy with Suspense to load components only when you need them. This helps the app load faster and feel more responsive.</p><h3>Final Thoughts</h3><p>Performance issues in React often creep in silently — small inefficiencies that add up as your app grows. These optimization patterns are widely applicable and can help improve performance and user experience across React applications of all sizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcdb280a45ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks vs Class Components: A Beginner-Friendly Comparison]]></title>
            <link>https://medium.com/@bhavyasavaliya.bs/react-hooks-vs-class-components-a-beginner-friendly-comparison-660a8349af0f?source=rss-7a0b86c92fe1------2</link>
            <guid isPermaLink="false">https://medium.com/p/660a8349af0f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[function-component]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[class-component]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Bhavyasavaliya]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 16:58:01 GMT</pubDate>
            <atom:updated>2025-06-17T16:58:01.346Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re new to React or have experience with class components, you may have heard that hooks have brought significant changes to the way React applications are developed.</p><p>Early in React’s history, class components were the standard approach., class components were everywhere. Managing state, dealing with lifecycle methods like componentDidMount, and passing data using context often felt confusing and repetitive. With the introduction of hooks, React development became simpler and cleaner.</p><p>In this blog, I want to walk you through the basics of four important hooks:</p><ul><li><strong>useState</strong></li><li><strong>useEffect</strong></li><li><strong>useRef</strong></li><li><strong>useContext</strong></li></ul><p>For each hook, I’ll show you what code looked like before hooks (using classes) and how much easier it is with hooks. I’ll also explain the pain points and benefits from my perspective.</p><h3>1. useState: Managing Local Component State</h3><p>Let’s start with the most used hook — <strong>useState</strong>.</p><p><strong>Without Hooks (Class Component)</strong></p><pre>class Counter extends React.Component {<br>  state = { count: 0 };<br><br>  increment = () =&gt; {<br>    this.setState({ count: this.state.count + 1 });<br>  };<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h3&gt;Count: {this.state.count}&lt;/h3&gt;<br>        &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p><strong>With Hook: useState (Function Component)</strong></p><pre>import React, { useState } from &quot;react&quot;;<br>function Counter() {<br>    const [count, setCount] = useState(0);<br>  <br>    return (<br>      &lt;div&gt;<br>        &lt;h3&gt;Count: {count}&lt;/h3&gt;<br>        &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }</pre><p><strong>What Was Difficult Without Hooks:</strong></p><ul><li>You had to use <strong><em>this.state, </em></strong><strong><em>this.setState,</em></strong> and bind functions.</li><li>Even for small components, you needed a class.</li><li>State logic wasn’t reusable.</li></ul><p><strong>Why useState is Better:</strong></p><ul><li>Much cleaner and easier to read.</li><li>No more dealing with <strong><em>this</em></strong>.</li><li>You can manage multiple states independently in one component.</li></ul><h3>2. useEffect: Doing Side Effects (e.g. API Calls, Timers)</h3><p>When your component needs to fetch data, set up a timer, or do something after render — you use useEffect.</p><p><strong>Without Hooks (Class Component)</strong></p><pre>class Timer extends React.Component {<br>  state = { seconds: 0 };<br><br>  componentDidMount() {<br>    this.interval = setInterval(() =&gt; {<br>      this.setState(prev =&gt; ({ seconds: prev.seconds + 1 }));<br>    }, 1000);<br>  }<br><br>  componentWillUnmount() {<br>    clearInterval(this.interval);<br>  }<br><br>  render() {<br>    return &lt;h3&gt;Time: {this.state.seconds} seconds&lt;/h3&gt;;<br>  }<br>}</pre><p><strong>With Hook: useEffect(Function Component)</strong></p><pre>import React, { useEffect} from &quot;react&quot;;<br>function Timer() {<br>  const [seconds, setSeconds] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; setSeconds(s =&gt; s + 1), 1000);<br>    return () =&gt; clearInterval(interval);<br>  }, []);<br><br>  return &lt;h3&gt;Time: {seconds} seconds&lt;/h3&gt;;<br>}</pre><p><strong>What Was Difficult Without Hooks:</strong></p><ul><li>You had to spread your logic across multiple lifecycle methods.</li><li>It was hard to keep related logic together.</li><li>Cleanup code (like stopping a timer) was messy.</li></ul><p><strong>Why useEffect is Better:</strong></p><ul><li>Everything lives in one place.</li><li>Cleanup is easy with the return function.</li><li>Execution is controlled by specifying dependencies in the array.</li></ul><h3>3. useRef: Getting a Reference to a DOM Element or Persistent Value</h3><p>If you’ve ever needed to directly access an input field or persist a value between renders without triggering a re-render — useRef is the way to go.</p><p><strong>Without Hooks (Class Component)</strong></p><pre>class FocusInput extends React.Component {<br>  constructor() {<br>    super();<br>    this.inputRef = React.createRef();<br>  }<br><br>  focus = () =&gt; {<br>    this.inputRef.current.focus();<br>  };<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;input ref={this.inputRef} type=&quot;text&quot; /&gt;<br>        &lt;button onClick={this.focus}&gt;Focus Input&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p><strong>With Hook: useRef (Function Component)</strong></p><pre>import React, { useRef} from &quot;react&quot;;<br>function FocusInput() {<br>    const inputRef = useRef(null);<br>  <br>    return (<br>      &lt;div&gt;<br>        &lt;input ref={inputRef} type=&quot;text&quot; /&gt;<br>        &lt;button onClick={() =&gt; inputRef.current.focus()}&gt;Focus Input&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }</pre><p><strong>What Was Hard Without Hooks:</strong></p><ul><li>You needed constructors and had to manage refs manually.</li><li>It made the component more complex.</li></ul><p><strong>Why useRef is Better:</strong></p><ul><li>You can declare and use it easily in functional components.</li><li>It’s perfect for keeping mutable values around without causing re-renders.</li></ul><h3>4. useContext: Accessing Global Data Easily</h3><p>When you want to pass down data (like theme or user info) to deeply nested components, <strong>useContext </strong>is your friend.</p><p><strong>Without Hooks (Class Component)</strong></p><pre>const ThemeContext = React.createContext(&#39;light&#39;);<br><br>class ThemedButton extends React.Component {<br>  static contextType = ThemeContext;<br><br>  render() {<br>    const theme = this.context;<br>    return &lt;button style={{ background: theme === &#39;dark&#39; ? &#39;#333&#39; : &#39;#eee&#39; }}&gt;<br>             Theme: {theme}<br>           &lt;/button&gt;;<br>  }<br>}</pre><p><strong>With Hook: useContext (Function Component)</strong></p><pre>import React, { useContext} from &quot;react&quot;;<br>const ThemeContext = React.createContext(&#39;light&#39;);<br><br>function ThemedButton() {<br>  const theme = useContext(ThemeContext);<br>  return &lt;button style={{ background: theme === &#39;dark&#39; ? &#39;#333&#39; : &#39;#eee&#39; }}&gt;<br>           Theme: {theme}<br>         &lt;/button&gt;;<br>}</pre><p><strong>What Was Hard Without Hooks:</strong></p><ul><li>You had to use <strong><em>static contextType</em></strong>.</li><li>It wasn’t easy to use multiple contexts at once.</li><li>More boilerplate.</li></ul><p><strong>Why useContext is Better:</strong></p><ul><li>Just call <strong><em>useContext </em></strong>in any functional component.</li><li>Clean and simple syntax.</li><li>Great for global state like auth, theme, user, etc.</li></ul><h3>Final Thoughts</h3><p>Hooks made React fun again. No more fighting with <strong>this</strong>, long lifecycle methods, or confusing state logic.</p><p>For those new to hooks, it is recommended to start by gradually converting class components to functional components using hooks. As familiarity with hooks increases, many developers find them to be a more efficient and maintainable approach to building React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=660a8349af0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>