<?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 Ralphbetta on Medium]]></title>
        <description><![CDATA[Stories by Ralphbetta on Medium]]></description>
        <link>https://medium.com/@ralphbetta?source=rss-e11d2b567227------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CjEwFG0MWOcARYpRimITQw.jpeg</url>
            <title>Stories by Ralphbetta on Medium</title>
            <link>https://medium.com/@ralphbetta?source=rss-e11d2b567227------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:15:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ralphbetta/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[Becoming a Python AI Engineer in this Modern AI Era: What It Takes Today vs. Before]]></title>
            <link>https://medium.com/@ralphbetta/becoming-a-python-ai-engineer-in-this-modern-ai-era-what-it-takes-today-vs-before-f4dc9d337653?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4dc9d337653</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 06:24:55 GMT</pubDate>
            <atom:updated>2026-04-24T06:24:55.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>Becoming a Python AI Engineer in the Modern AI Era: What It Takes Today vs. Before</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yp0wi-LQ4LelnCJ_HuJZQ.png" /></figure><p>Artificial Intelligence has evolved dramatically over the past decade. In the past, becoming an <strong>AI engineer</strong> required deep academic expertise and years of experience building machine learning models from scratch. Today, the landscape has shifted. Thanks to powerful tools, APIs, and pre-trained models, developers can build advanced AI systems without needing to reinvent the underlying algorithms.</p><p>For anyone considering becoming a <strong>Python AI Engineer</strong>, understanding this shift is critical. This article explains how the role has evolved, what skills are required today, and whether it is a worthwhile career path.</p><h3>Who Is a Python AI Engineer?</h3><p>A <strong>Python AI Engineer</strong> is a developer who designs, builds, and deploys systems that use artificial intelligence.</p><p>Their work often includes:</p><ul><li>Building AI-powered applications</li><li>Integrating machine learning models into software systems</li><li>Creating chatbots and intelligent assistants</li><li>Processing large datasets</li><li>Deploying AI systems into production</li></ul><p>Python dominates AI development because of its strong ecosystem of libraries and frameworks such as:</p><ul><li>TensorFlow</li><li>PyTorch</li><li>Scikit-learn</li></ul><p>These tools make it easier to build and train machine learning models.</p><p>However, the role of the AI engineer has changed significantly in recent years.</p><h3>The Old Era of AI Engineering (Manual Machine Learning)</h3><p>Before the rise of large language models and AI platforms, AI engineers had to build most systems manually.</p><p>The process typically involved several complex steps.</p><h4>Data Collection</h4><p>Engineers needed to gather large datasets for training models.</p><h4>Data Cleaning</h4><p>Raw data often contained errors, missing values, and inconsistencies that needed to be corrected.</p><h4>Feature Engineering</h4><p>This was one of the most difficult tasks. Engineers manually designed input features that the machine learning model could understand.</p><h4>Model Selection</h4><p>Engineers chose algorithms such as:</p><ul><li>Logistic Regression</li><li>Decision Trees</li><li>Random Forest</li><li>Support Vector Machines</li></ul><h4>Model Training</h4><p>Using frameworks like TensorFlow or PyTorch, engineers trained models on GPUs.</p><h4>Hyperparameter Tuning</h4><p>Fine-tuning parameters such as learning rate, batch size, and model architecture required experimentation and deep understanding.</p><h4>Deployment</h4><p>Finally, engineers packaged models into APIs or services for production use.</p><p>This workflow required <strong>strong mathematics knowledge</strong>, including:</p><ul><li>Linear Algebra</li><li>Probability and Statistics</li><li>Calculus</li></ul><p>Because of this complexity, many AI engineers previously needed advance knowledge in computer science or data science.</p><h3>The Modern AI Era: AI Application Engineering</h3><p>Today, the AI landscape looks very different.</p><p>Instead of building models from scratch, developers can leverage powerful pre-trained models like:</p><ul><li>GPT-4</li><li>Claude</li><li>Llama</li></ul><p>These models already understand language, reasoning, and code.</p><p>As a result, the role of AI engineers has shifted toward <strong>building AI-powered systems using these models</strong>.</p><p>This new discipline is often called <strong>AI Engineering</strong> or <strong>LLM Engineering</strong>.</p><p>Instead of focusing mainly on model training, engineers now focus on:</p><ul><li>Integrating models into applications</li><li>Designing AI workflows</li><li>Managing context and prompts</li><li>Connecting models to company data</li></ul><h3>Core Skills Required for a Python AI Engineer Today</h3><p>Modern AI engineers require a combination of <strong>software engineering and AI integration skills</strong>.</p><h4>Python Programming</h4><p>Python remains the foundation of AI development.</p><p>Important libraries include:</p><ul><li>NumPy</li><li>Pandas</li><li>Requests</li><li>FastAPI</li></ul><p>Engineers often build APIs that allow applications to communicate with AI services.</p><h4>Large Language Model (LLM) Engineering</h4><p>A major part of modern AI development is working with LLMs.</p><p>Key skills include:</p><ul><li>Prompt engineering</li><li>Context window management</li><li>Response evaluation</li><li>System instruction design</li></ul><p>These skills determine how effectively the AI responds to users.</p><h4>Retrieval-Augmented Generation (RAG)</h4><p>RAG is one of the most important concepts in modern AI systems.</p><p>Instead of training a model on company data, engineers allow the AI to <strong>retrieve information from external sources</strong>.</p><p>This allows systems to answer questions based on:</p><ul><li>company documents</li><li>knowledge bases</li><li>PDFs</li><li>databases</li></ul><p>RAG systems typically use vector databases such as:</p><ul><li>Pinecone</li><li>Weaviate</li><li>Chroma</li></ul><h4>AI Frameworks</h4><p>To simplify building AI applications, engineers often use orchestration frameworks like:</p><ul><li>LangChain</li><li>LlamaIndex</li><li>Haystack</li></ul><p>These tools help developers build pipelines that combine prompts, retrieval, tools, and models.</p><h4>AI Agents</h4><p>Another emerging trend is <strong>AI agents</strong>.</p><p>Agents are AI systems that can perform tasks autonomously.</p><p>Examples include:</p><ul><li>research assistants</li><li>coding assistants</li><li>autonomous customer support systems</li></ul><p>Frameworks such as:</p><ul><li>AutoGPT</li><li>CrewAI</li></ul><p>allow engineers to build multi-step AI workflows.</p><h4>Deployment and Infrastructure</h4><p>AI engineers must also know how to deploy systems.</p><p>Typical tools include:</p><ul><li>FastAPI for building APIs</li><li>Docker for containerization</li><li>cloud platforms for hosting</li><li>GPU inference systems</li></ul><p>Deployment skills ensure AI systems run efficiently in real-world environments.</p><h3>The Biggest Shift: From Model Builders to System Builders</h3><p>The most important transformation in AI engineering is this:</p><p><strong>Old Approach</strong></p><ul><li>Build machine learning models</li></ul><p><strong>Modern Approach</strong></p><ul><li>Build AI-powered systems using existing models</li></ul><p>This shift has made AI development <strong>much more accessible</strong> to software engineers.</p><p>Developers who already understand backend systems, APIs, and data pipelines can transition into AI engineering more easily.</p><h3>Typical Projects for Modern AI Engineers</h3><p>To demonstrate real-world skills, aspiring AI engineers often build projects such as:</p><ul><li>AI chatbots for businesses</li><li>document question-answering systems</li><li>AI-powered research assistants</li><li>AI code generation tools</li><li>voice assistants using speech-to-text and text-to-speech</li></ul><p>These projects showcase the ability to combine AI models with software infrastructure.</p><h3>Is Becoming a Python AI Engineer Worth It?</h3><p>The demand for AI engineers continues to grow rapidly as businesses integrate AI into their products.</p><p>Advantages of the field include:</p><ul><li>high global demand</li><li>competitive salaries</li><li>ability to build impactful systems</li><li>opportunities in startups and large tech companies</li></ul><p>However, it also requires continuous learning because AI technologies are evolving quickly.</p><h3>Conclusion</h3><p>The barrier to entry for AI development has decreased significantly compared to the past. While earlier AI engineers needed deep mathematical expertise, modern engineers can focus on <strong>building intelligent systems using powerful existing models</strong>.</p><p>Python remains the central language for this work due to its rich ecosystem and flexibility.</p><p>For developers who enjoy solving complex problems and building innovative applications, becoming a Python AI engineer offers a promising and exciting career path.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4dc9d337653" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Guide to React useEffect]]></title>
            <link>https://medium.com/@ralphbetta/advanced-guide-to-react-useeffect-86b1abfd57bd?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b1abfd57bd</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 06:35:26 GMT</pubDate>
            <atom:updated>2026-04-22T06:35:26.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ev2xluRRdxfogrcaP4moAg.png" /></figure><p>At surface level, useEffect looks simple: run some code after render. But in real-world React applications—especially at scale—it becomes one of the most misunderstood and misused hooks.</p><p>Many bugs in production React systems come from:</p><ul><li>incorrect dependencies</li><li>stale closures</li><li>improper cleanup</li><li>treating useEffect like a lifecycle method</li></ul><p>To use useEffect effectively, you need to shift your mental model from <em>“when does this run?”</em> to:</p><blockquote><strong><em>“What external system am I synchronizing with?”</em></strong></blockquote><h3>1. The True Purpose of useEffect</h3><p>useEffect is not for “running code after render.”</p><p>It is for <strong>synchronizing your component with something outside React’s control</strong>.</p><p>Think of React as a pure rendering engine:</p><ul><li>Input → JSX → UI</li></ul><p>Anything outside that flow is considered a <strong>side effect</strong>:</p><ul><li>Fetching data from an API</li><li>Subscribing to a WebSocket</li><li>Updating the browser title</li><li>Listening to DOM events</li><li>Writing to localStorage</li></ul><h3>Example: Synchronizing with the Browser</h3><pre>useEffect(() =&gt; {<br>  document.title = `Dashboard`;<br>}, []);</pre><h3>What’s really happening?</h3><ul><li>React renders your component</li><li>After the DOM is updated, this effect runs</li><li>It updates something React does not control: the browser tab title</li></ul><p>This is synchronization with an external system (the browser environment).</p><h3>2. Understanding the Execution Lifecycle</h3><p>A common mistake is assuming useEffect behaves like:</p><ul><li>componentDidMount</li><li>componentDidUpdate</li><li>componentWillUnmount</li></ul><p>That mapping is <strong>incomplete and misleading</strong>.</p><h3>What actually happens:</h3><ol><li>React renders your component (pure function)</li><li>React commits changes to the DOM</li><li>React runs your effect</li></ol><h3>Cleanup Flow</h3><p>If your effect returns a function:</p><pre>useEffect(() =&gt; {<br>  console.log(&quot;Effect runs&quot;);<br>return () =&gt; {<br>    console.log(&quot;Cleanup runs&quot;);<br>  };<br>}, []);</pre><h4>Execution order:</h4><ul><li>Mount → “Effect runs”</li><li>Unmount → “Cleanup runs”</li></ul><p>But when dependencies exist:</p><pre>useEffect(() =&gt; {<br>  console.log(&quot;Effect runs&quot;);<br>return () =&gt; {<br>    console.log(&quot;Cleanup runs&quot;);<br>  };<br>}, [value]);</pre><h4>Execution becomes:</h4><ul><li>Initial render → Effect runs</li><li>value changes →</li><li>Cleanup runs (old effect)</li><li>Effect runs (new value)</li></ul><p>Cleanup always runs <strong>before the next effect</strong>, not just on unmount.</p><h3>3. Dependency Array: The Heart of Correctness</h3><p>The dependency array is not optional decoration.</p><p>It defines:</p><blockquote><strong><em>When should this synchronization re-run?</em></strong></blockquote><h3>Example: Fetching Data</h3><pre>useEffect(() =&gt; {<br>  fetch(`/api/users/${userId}`)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; setUser(data));<br>}, [userId]);</pre><h3>Why [userId]?</h3><p>Because:</p><ul><li>The data we want depends on userId</li><li>When userId changes, the external system (API) must be re-synced</li></ul><h3>What happens if you remove it?</h3><pre>useEffect(() =&gt; {<br>  fetch(`/api/users/${userId}`);<br>}, []);</pre><p>Now:</p><ul><li>The effect runs only once</li><li>If userId changes, the UI and data go out of sync</li></ul><p>This is how subtle production bugs happen.</p><h3>4. Stale Closures: The Hidden Trap</h3><p>JavaScript closures capture values at the time the function is created.</p><p>This becomes dangerous inside useEffect.</p><h3>Example</h3><pre>useEffect(() =&gt; {<br>  const interval = setInterval(() =&gt; {<br>    console.log(count);<br>  }, 1000);<br>return () =&gt; clearInterval(interval);<br>}, []);</pre><h3>What you expect:</h3><ul><li>Logs updated count</li></ul><h3>What actually happens:</h3><ul><li>Logs the <strong>initial value forever</strong></li></ul><h3>Why?</h3><p>Because:</p><ul><li>The effect runs once</li><li>The callback inside setInterval captures the initial count</li><li>It never sees updates</li></ul><h3>Fix 1: Add count as a dependency</h3><pre>useEffect(() =&gt; {<br>  const interval = setInterval(() =&gt; {<br>    console.log(count);<br>  }, 1000);<br>return () =&gt; clearInterval(interval);<br>}, [count]);</pre><p>Now:</p><ul><li>Every time count changes, the interval resets with the latest value</li></ul><h3>Trade-off</h3><p>This works, but:</p><ul><li>It recreates the interval every time</li><li>Not always efficient</li></ul><h3>Fix 2: Use a Ref (Advanced Pattern)</h3><pre>const countRef = useRef(count);<br><br>useEffect(() =&gt; {<br>  countRef.current = count;<br>}, [count]);<br>useEffect(() =&gt; {<br>  const interval = setInterval(() =&gt; {<br>    console.log(countRef.current);<br>  }, 1000);<br>  return () =&gt; clearInterval(interval);<br>}, []);</pre><h3>Why this works:</h3><ul><li>useRef stores a mutable value</li><li>The interval always reads the latest value from countRef</li><li>The effect doesn’t need to re-run</li></ul><p>👉 This pattern is common in real-time systems (e.g., chat apps, dashboards).</p><h3>5. Splitting Effects: A Senior-Level Practice</h3><p>A common anti-pattern is writing one large effect that does everything.</p><h3>Bad Example</h3><pre>useEffect(() =&gt; {<br>  fetchUser(userId);<br>  document.title = userId;<br>window.addEventListener(&quot;resize&quot;, handleResize);<br>  return () =&gt; {<br>    window.removeEventListener(&quot;resize&quot;, handleResize);<br>  };<br>}, [userId]);</pre><h3>Why this is bad:</h3><ul><li>Multiple responsibilities mixed together</li><li>Harder to debug</li><li>Harder to maintain</li></ul><h3>Better Approach</h3><pre>// Data fetching<br>useEffect(() =&gt; {<br>  fetchUser(userId);<br>}, [userId]);<br><br>// Document title<br>useEffect(() =&gt; {<br>  document.title = `User: ${userId}`;<br>}, [userId]);<br><br>// Event listener<br>useEffect(() =&gt; {<br>  window.addEventListener(&quot;resize&quot;, handleResize);<br>  return () =&gt; window.removeEventListener(&quot;resize&quot;, handleResize);<br>}, []);</pre><p>👉 Each effect answers one question:</p><ul><li>“When should I fetch?”</li><li>“When should I update title?”</li><li>“When should I attach listeners?”</li></ul><h3>6. Race Conditions in API Calls</h3><p>In fast-changing UIs, users can trigger multiple requests quickly.</p><h3>Problem Scenario</h3><pre>useEffect(() =&gt; {<br>  fetch(`/api/user/${userId}`)<br>    .then(res =&gt; res.json())<br>    .then(setUser);<br>}, [userId]);</pre><p>If userId changes quickly:</p><ul><li>Request A starts</li><li>Request B starts</li><li>Request B finishes first → correct</li><li>Request A finishes later → overwrites correct data ❌</li></ul><h3>Solution: AbortController</h3><pre>useEffect(() =&gt; {<br>  const controller = new AbortController();<br>fetch(`/api/user/${userId}`, {<br>    signal: controller.signal,<br>  })<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; setUser(data))<br>    .catch(err =&gt; {<br>      if (err.name !== &quot;AbortError&quot;) {<br>        console.error(err);<br>      }<br>    });<br>  return () =&gt; controller.abort();<br>}, [userId]);</pre><h3>What this does:</h3><ul><li>Cancels previous requests when userId changes</li><li>Prevents outdated data from overwriting new state</li></ul><h3>7. Infinite Loops: A Design Smell</h3><h3>Problem</h3><pre>useEffect(() =&gt; {<br>  setData(process(data));<br>}, [data]);</pre><h3>What happens:</h3><ul><li>data changes → effect runs</li><li>effect updates data → triggers effect again</li><li>infinite loop</li></ul><h3>Root Cause</h3><p>You are:<br>using useEffect for <strong>derived state</strong></p><h3>Correct Approach</h3><pre>const processedData = process(data);</pre><p>No effect needed</p><h3>8. useEffect vs useLayoutEffect</h3><p>Both run after render, but timing differs.</p><ul><li>useEffect: after paint (non-blocking)</li><li>useLayoutEffect: before paint (blocking)</li></ul><h3>Example</h3><pre>useLayoutEffect(() =&gt; {<br>  const height = ref.current.offsetHeight;<br>  setHeight(height);<br>}, []);</pre><h3>Why use it?</h3><ul><li>You need layout measurement before the browser paints</li><li>Prevents flickering UI</li></ul><h3>9. React Strict Mode (Why Effects Run Twice)</h3><p>In development, React may run effects twice.</p><p>This is intentional.</p><h3>Why?</h3><p>To detect:</p><ul><li>side effects that are not properly cleaned up</li><li>unsafe assumptions</li></ul><h3>Example</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;Running effect&quot;);<br>}, []);</pre><p>In development:</p><ul><li>This logs twice</li></ul><h3>Key Insight</h3><p>Your effects must be:<br> <strong>idempotent</strong> (safe to run multiple times)</p><p>At a senior level, useEffect is less about syntax and more about discipline.</p><p>The key principles:</p><ul><li>Treat effects as <strong>synchronization boundaries</strong></li><li>Be precise with dependencies</li><li>Avoid mixing responsibilities</li><li>Always think about cleanup</li><li>Understand closures deeply</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b1abfd57bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable React Architecture for Large Applications]]></title>
            <link>https://medium.com/@ralphbetta/scalable-react-architecture-for-large-applications-f28ef0ed8e8f?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/f28ef0ed8e8f</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 10:28:13 GMT</pubDate>
            <atom:updated>2026-04-10T10:28:13.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXIcF0UMxH8SRYhsJ15BBg.png" /></figure><p><strong>Modern React applications rarely stay small.</strong></p><p>What often begins as a simple interface can quickly evolve into a <strong>large production system</strong> with dozens of pages, complex state management, multiple teams contributing code, and thousands of components.</p><p>Without a well-defined architecture, React projects tend to suffer from:</p><ul><li>Disorganized folder structures</li><li>Tight coupling between components</li><li>Difficult debugging and testing</li><li>Performance bottlenecks</li><li>Poor developer onboarding</li><li>Reduced maintainability</li></ul><p>As applications scale, <strong>architecture becomes just as important as functionality</strong>.</p><p>A scalable React architecture ensures:</p><ul><li>Maintainable codebases</li><li>Clear separation of responsibilities</li><li>Easier collaboration across teams</li><li>Efficient performance optimization</li><li>Faster feature development</li></ul><p>This article explores <strong>real-world architectural patterns used in production-scale React applications</strong>, including feature-based organization, state management strategies, service layers, performance optimization, and testing approaches.</p><h3>Core Principles of Scalable React Architecture</h3><p>A scalable frontend architecture is built around a few key engineering principles.</p><h3>1. Separation of Concerns</h3><p>Each part of the application should have a <strong>clear responsibility</strong>.</p><p>For example:</p><pre>| Layer         | Responsibility          |<br>| ------------- | ----------------------- |<br>| UI Components | Rendering interface     |<br>| Hooks         | Managing reusable logic |<br>| Services      | API communication       |<br>| Store         | Global state management |<br>| Utils         | Shared helper functions |</pre><p>This separation ensures components remain <strong>simple and focused</strong>.</p><p>Better approach:</p><ul><li>API logic in <strong>services</strong></li><li>UI in <strong>components</strong></li><li>Data logic in <strong>hooks</strong></li></ul><h3>2. Feature-Based Architecture</h3><p>Instead of grouping files by <strong>type</strong>, scalable applications group them by <strong>feature</strong>.</p><p>Better structure:</p><pre>features/<br>   users/<br>   authentication/<br>   dashboard/</pre><p>Each feature becomes a <strong>self-contained module</strong>.</p><p>Benefits:</p><ul><li>Easier navigation</li><li>Independent development</li><li>Better code ownership</li><li>Reduced coupling</li></ul><h3>3. Reusability and Modular Design</h3><p>Reusable modules reduce duplication and improve maintainability.</p><p>Examples:</p><ul><li>Shared UI components</li><li>Custom hooks</li><li>Utility functions</li><li>API services</li></ul><p>Reusable logic example:</p><pre><br>import { useState, useEffect } from &quot;react&quot;;<br><br>export function useUsers() {<br>  const [users, setUsers] = useState([]);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);<br><br>  const fetchUsers = async () =&gt; {<br>    try {<br>      setLoading(true);<br>      const res = await fetch(&quot;/api/users&quot;);<br>      const data = await res.json();<br>      setUsers(data);<br>    } catch (err) {<br>      setError(err.message);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    fetchUsers();<br>  }, []);<br><br>  return { users, loading, error, refetch: fetchUsers };<br>}</pre><p>This hook can now be reused across the application.</p><h3>4. Scalability Considerations</h3><p>When designing architecture, consider:</p><ul><li>Team size</li><li>Code ownership</li><li>Performance constraints</li><li>Testing strategy</li><li>Deployment pipeline</li></ul><p>A scalable architecture must support <strong>growth in both codebase and team size</strong>.</p><h3>Recommended Folder Structure for Large React Applications</h3><p>A widely used structure for large applications looks like this:</p><pre>src<br>│<br>├── app<br>│   ├── store<br>│   ├── providers<br>│<br>├── features<br>│   ├── auth<br>│   ├── users<br>│   ├── dashboard<br>│<br>├── shared<br>│   ├── components<br>│   ├── hooks<br>│   ├── services<br>│   ├── utils<br>│   ├── types<br>│<br>├── routes<br>│<br>├── assets<br>│<br>├── config<br>│<br>└── main.tsx</pre><h3><strong>features</strong></h3><p>Feature modules representing business domains.</p><p>Example:</p><pre>features/users<br>features/auth<br>features/notifications</pre><p><strong>shared</strong></p><p>Reusable code across the application.</p><pre>shared/components<br>shared/hooks<br>shared/utils<br>shared/services</pre><p><strong>app</strong></p><p>Application configuration.</p><p>Examples:</p><ul><li>Global store</li><li>Context providers</li><li>App-level setup</li></ul><p><strong>routes</strong></p><p>Central routing configuration.</p><h3>State Management Strategies</h3><p>State management is one of the most critical aspects of large React applications.</p><p>Not all state should be global.</p><h3>1. Local Component State</h3><p>Use local state when data is <strong>only needed inside a component</strong>.</p><p>Example:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      {count}<br>    &lt;/button&gt;<br>  );<br>}Use local state for:</pre><ul><li>Form inputs</li><li>UI toggles</li><li>Temporary state</li></ul><h3>2. Context API</h3><p>Useful for <strong>shared state across multiple components</strong>.</p><p>Example:</p><pre>const AuthContext = createContext();<br><br>export function AuthProvider({ children }) {<br>  const [user, setUser] = useState(null);<br><br>  return (<br>    &lt;AuthContext.Provider value={{ user, setUser }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}</pre><p>Best used for:</p><ul><li>Authentication state</li><li>Theme settings</li><li>Localization</li></ul><h3>3. Redux / Zustand / React Query</h3><p>Large applications often combine multiple state tools.</p><h3>Redux</h3><p>Best for <strong>complex global state</strong>.</p><h3>Zustand</h3><p>Lightweight alternative to Redux.</p><h3>React Query</h3><p>Best for <strong>server state</strong>.</p><p>Example using React Query:</p><pre>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>export function useUsers() {<br>  return useQuery({<br>    queryKey: [&quot;users&quot;],<br>    queryFn: fetchUsers<br>  });<br>}Rule of thumb:</pre><p>State TypeToolUI stateuseStateShared UI stateContextServer stateReact QueryComplex global stateRedux</p><h3>Structuring Features in Large Applications</h3><p>Each feature should contain its own <strong>logic, components, and API layer</strong>.</p><p>Example: <strong>User Management</strong></p><pre>features/users<br>│<br>├── components<br>│   ├── UserList.jsx<br>│   ├── UserCard.jsx<br>│<br>├── hooks<br>│   ├── useUsers.js<br>│<br>├── services<br>│   ├── usersApi.js<br>│<br>├── types<br>│   ├── user.types.ts<br>│<br>└── pages<br>    ├── UsersPage.jsx</pre><h3>API Layer</h3><pre>export async function fetchUsers() {<br>  const res = await fetch(&quot;/api/users&quot;);<br>  return res.json();<br>}</pre><h3>Custom Hook</h3><pre>import { useQuery } from &quot;@tanstack/react-query&quot;;<br>import { fetchUsers } from &quot;../services/usersApi&quot;;<br><br>export function useUsers() {<br>  return useQuery({<br>    queryKey: [&quot;users&quot;],<br>    queryFn: fetchUsers<br>  });<br>}</pre><h3>UI Component</h3><pre>export function UserList() {<br>  const { data, isLoading } = useUsers();<br><br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map(user =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>This keeps the component <strong>clean and focused on UI rendering</strong>.</p><h3>Reusable Components and Design Systems</h3><p>Large applications benefit greatly from a <strong>design system</strong>.</p><p>A design system ensures:</p><ul><li>Consistent UI</li><li>Reusable components</li><li>Faster development</li></ul><p>Example shared component:</p><pre>shared/components/Button</pre><pre>export function Button({ children, ...props }) {<br>  return (<br>    &lt;button className=&quot;btn-primary&quot; {...props}&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>Using <strong>Atomic Design</strong>:</p><p>LevelExampleAtomsButton, InputMoleculesSearchBarOrganismsNavbar</p><p>This structure improves <strong>UI consistency and reuse</strong>.</p><h3>API and Service Layer</h3><p>Never place API calls directly inside UI components.</p><p>Instead, create a <strong>service layer</strong>.</p><p>Example:</p><pre>shared/services/apiClient.js</pre><pre>export async function apiClient(url, options) {<br>  const response = await fetch(url, options);<br>  return response.json();<br>}</pre><p>Feature API:</p><pre>import { apiClient } from &quot;@/shared/services/apiClient&quot;;<br><br>export function fetchUsers() {<br>  return apiClient(&quot;/users&quot;);<br>}</pre><p>Benefits:</p><ul><li>Centralized API logic</li><li>Easier testing</li><li>Easier error handling</li><li>Better maintainability</li></ul><h3>Performance Optimization Strategies</h3><p>Performance matters significantly in large React applications.</p><h3>React.memo</h3><p>Prevents unnecessary re-renders.</p><pre>const UserCard = React.memo(function UserCard({ user }) {<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>});</pre><h3>Lazy Loading</h3><p>Load components only when needed.</p><pre>const Dashboard = React.lazy(() =&gt; import(&quot;./Dashboard&quot;));</pre><h3>Suspense</h3><p>Used with lazy loading.</p><pre>&lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>  &lt;Dashboard /&gt;<br>&lt;/Suspense&gt;</pre><h3>Code Splitting</h3><p>Split bundles to improve load times.</p><p>Example with routes:</p><pre>const UsersPage = lazy(() =&gt; import(&quot;../features/users/pages/UsersPage&quot;));</pre><h3>Memoization</h3><h3>useMemo</h3><pre>const sortedUsers = useMemo(() =&gt; {<br>  return users.sort((a, b) =&gt; a.name.localeCompare(b.name));<br>}, [users]);</pre><h3>useCallback</h3><pre>const handleClick = useCallback(() =&gt; {<br>  console.log(&quot;clicked&quot;);<br>}, []);</pre><p>These optimizations prevent unnecessary computations and re-renders.</p><h3>Routing Structure for Scalable Apps</h3><p>Centralize routing configuration.</p><p>Example using <strong>React Router</strong>.</p><pre>routes<br>   index.jsx<br>   protectedRoutes.jsx</pre><p>Example:</p><pre>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import UsersPage from &quot;@/features/users/pages/UsersPage&quot;;<br><br>export function AppRoutes() {<br>  return (<br>    &lt;Routes&gt;<br>      &lt;Route path=&quot;/users&quot; element={&lt;UsersPage /&gt;} /&gt;<br>    &lt;/Routes&gt;<br>  );<br>}</pre><p>Benefits:</p><ul><li>Clear navigation structure</li><li>Easier code splitting</li><li>Better maintainability</li></ul><h3>Testing Strategy</h3><p>Testing ensures long-term reliability.</p><p>Three levels of testing are recommended.</p><h3>1. Unit Testing</h3><p>Tests individual functions or components.</p><p>Example with Jest:</p><pre>test(&quot;adds numbers&quot;, () =&gt; {<br>  expect(add(2, 3)).toBe(5);<br>});</pre><h3>2. Component Testing</h3><p>Testing React components.</p><p>Using React Testing Library:</p><pre>render(&lt;Button&gt;Click&lt;/Button&gt;);<br>expect(screen.getByText(&quot;Click&quot;)).toBeInTheDocument();</pre><h3>3. Integration Testing</h3><p>Tests interactions between components and APIs.</p><p>Example:</p><ul><li>User login flow</li><li>Checkout process</li><li>Dashboard data fetching</li></ul><h3>Best Practices Used in Production</h3><p>Large companies typically follow these practices:</p><ul><li>Feature-based architecture</li><li>Clear separation between UI and data logic</li><li>API abstraction layers</li><li>Strong typing with TypeScript</li><li>Centralized error handling</li><li>Code splitting and lazy loading</li><li>Design system for reusable components</li><li>Automated testing pipelines</li></ul><h3>Common Mistakes When Scaling React Apps</h3><p>Many React projects struggle because of architectural mistakes.</p><h3>1. Flat folder structures</h3><pre>components/<br>components/<br>components/</pre><p>Hard to maintain.</p><h3>2. API calls inside UI components</h3><p>Creates tight coupling.</p><h3>3. Overusing global state</h3><p>Not all data should live in Redux.</p><h3>4. No feature boundaries</h3><p>Everything becomes interconnected.</p><h3>5. Ignoring performance early</h3><p>Large applications must consider:</p><ul><li>bundle size</li><li>re-renders</li><li>network requests</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f28ef0ed8e8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redux Toolkit Query (RTK Query) in Modern React Applications]]></title>
            <link>https://medium.com/@ralphbetta/understanding-redux-toolkit-query-rtk-query-in-modern-react-applications-1066f94d1a44?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/1066f94d1a44</guid>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[rtk-query]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 00:00:22 GMT</pubDate>
            <atom:updated>2026-03-19T00:00:22.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jt738NyIckUt9Pjq2ZcLA.png" /></figure><p>Redux has been one of the most widely used state management libraries in the React ecosystem. For years, developers used traditional Redux patterns involving actions, reducers, constants, middleware, and asynchronous logic through tools like Redux Thunk or Redux Saga. While powerful, that approach often led to a lot of boilerplate, especially when handling API requests.</p><p>Redux Toolkit Query, commonly called <strong>RTK Query</strong>, was introduced to solve that problem. It provides a modern, efficient, and scalable way to fetch, cache, update, and synchronize server data in Redux applications.</p><p>A good RTK Query setup typically uses apiSlice.injectEndpoints, builder.query, builder.mutation, and auto-generated hooks such as useGetProductsQuery and useCreateProductMutation. That means the application is using Redux Toolkit Query as its API and server-state management solution.</p><h3>What is RTK Query?</h3><p>RTK Query is a data fetching and caching tool built into Redux Toolkit. It is designed to handle API communication in a structured and predictable way while reducing the amount of code developers need to write.</p><p>Instead of manually creating:</p><ul><li>action types</li><li>action creators</li><li>reducers</li><li>async thunks</li><li>loading state</li><li>error state</li><li>caching logic</li></ul><p>RTK Query lets you define all of that in one central API slice.</p><p>In simple terms, RTK Query gives you:</p><ul><li>a single place to define API endpoints</li><li>built-in request lifecycle handling</li><li>caching out of the box</li><li>automatic React hooks</li><li>refetching and invalidation support</li><li>less boilerplate than traditional Redux async logic</li></ul><h3>Why RTK Query was introduced</h3><p>Before RTK Query, fetching data in Redux often looked like this:</p><ul><li>Dispatch a “request started” action</li><li>Make the API call</li><li>Dispatch a “request success” action with data</li><li>Dispatch a “request failed” action on error</li><li>Store loading, success, and error states in reducers</li><li>Rebuild the same logic for every API endpoint</li></ul><p>That got repetitive fast.</p><p>RTK Query was designed to make server-state management easier by handling the repetitive parts automatically.</p><p>This is important because <strong>server state</strong> is different from <strong>client state</strong>.</p><h3>Client state vs server state</h3><p><strong>Client state</strong> is local application state such as:</p><ul><li>modal visibility</li><li>selected tab</li><li>sidebar open/closed</li><li>theme mode</li><li>form draft values</li></ul><p><strong>Server state</strong> is data that comes from a backend, such as:</p><ul><li>products</li><li>customer orders</li><li>inventory counts</li><li>discount coupons</li><li>shipping settings</li><li>user reviews</li></ul><p>RTK Query is built mainly for <strong>server state</strong>.</p><h3>The pattern this code uses</h3><p>A typical RTK Query project follows the API slice architecture.</p><p>It often starts by importing a base API slice:</p><pre>import { apiSlice } from &quot;../../app/api/apiSlice&quot;;</pre><p>That usually means a root API configuration already exists somewhere else in the app. Then a feature file extends it using:</p><pre>apiSlice.injectEndpoints({<br>  endpoints: (builder) =&gt; ({<br>    ...<br>  }),<br>});</pre><p>This is a common scaling strategy in large applications. Instead of putting every endpoint in one huge file, you define a base API slice and then inject feature-specific endpoints into it.</p><p>In an e-commerce admin dashboard, one file might handle endpoints related to:</p><ul><li>products</li><li>categories</li><li>orders</li><li>customers</li><li>coupons</li><li>notifications</li><li>payments</li><li>inventory updates</li></ul><p>So architecturally, this is a <strong>feature-based RTK Query endpoint module</strong>.</p><h3>Core RTK Query concepts</h3><p>To understand RTK Query well, it helps to know the main concepts it uses.</p><h3>1. The API slice</h3><p>The API slice is the central service definition for your backend communication.</p><p>A typical base API looks like this:</p><pre>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;</pre><pre>export const apiSlice = createApi({<br>  reducerPath: &quot;api&quot;,<br>  baseQuery: fetchBaseQuery({ baseUrl: &quot;/api&quot; }),<br>  tagTypes: [&quot;Orders&quot;, &quot;Products&quot;, &quot;Notifications&quot;],<br>  endpoints: () =&gt; ({}),<br>});</pre><p>This base slice:</p><ul><li>registers RTK Query in Redux</li><li>sets the base URL</li><li>defines reusable cache tags</li><li>provides a place for endpoint injection</li></ul><p>Then feature files add endpoints with injectEndpoints.</p><h3>2. Queries</h3><p>A <strong>query</strong> is used for fetching data.</p><p>Example:</p><pre>getProducts: builder.query({<br>  query: () =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;GET&quot;,<br>  }),<br>  keepUnusedDataFor: 60,<br>  transformResponse: (response) =&gt; response,<br>}),</pre><p>Queries are for read operations such as:</p><ul><li>get products</li><li>get categories</li><li>get order history</li><li>get notifications</li><li>get payment summaries</li></ul><p>In React, RTK Query automatically generates hooks for them:</p><pre>const { data, error, isLoading } = useGetProductsQuery();</pre><p>That means you do not need to manually dispatch an action or write reducers for loading and error states.</p><h3>3. Mutations</h3><p>A <strong>mutation</strong> is used for creating, updating, or deleting data.</p><p>Example:</p><pre>createProduct: builder.mutation({<br>  query: (data) =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;POST&quot;,<br>    body: data,<br>  }),<br>}),</pre><p>Mutations are for write operations such as:</p><ul><li>create</li><li>update</li><li>delete</li><li>confirm payment</li><li>upload image</li><li>apply discount</li></ul><p>React hooks are also auto-generated:</p><pre>const [createProduct, { isLoading, error, data }] = useCreateProductMutation();</pre><p>You call the mutation manually when needed:</p><pre>await createProduct(productData);</pre><h3>4. Auto-generated hooks</h3><p>One of the nicest parts of RTK Query is that it creates React hooks for every endpoint you define.</p><p>From this:</p><pre>getOrders: builder.query({...})</pre><p>RTK Query generates:</p><pre>useGetOrdersQuery</pre><p>From this:</p><pre>updateOrderStatus: builder.mutation({...})</pre><p>It generates:</p><pre>useUpdateOrderStatusMutation</pre><p>That removes a lot of glue code.</p><h3>5. Response transformation</h3><p>Some endpoints use transformResponse.</p><p>Example:</p><pre>getAllOrders: builder.query({<br>  query: () =&gt; &quot;/orders&quot;,<br>  keepUnusedDataFor: 60,<br>  transformResponse: (response) =&gt; response.data,<br>}),</pre><p>This is useful when your backend wraps actual payloads inside a larger object.</p><p>For example, if the server returns:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;message&quot;: &quot;Orders fetched successfully&quot;,<br>  &quot;data&quot;: [...]<br>}</pre><p>You can extract only data so components receive a cleaner structure.</p><p>Without transformation, components would need to do:</p><pre>data?.data</pre><p>With transformation, they can do:</p><pre>data</pre><p>That keeps UI components cleaner.</p><h3>6. Cache management</h3><p>RTK Query caches fetched data automatically.</p><p>If a component calls:</p><pre>useGetProductsQuery();</pre><p>RTK Query stores the result in Redux. If another component requests the same data, RTK Query can reuse the cached result instead of making another network request.</p><p>Example configuration:</p><pre>keepUnusedDataFor: 60</pre><p>This means cached data stays around for 60 seconds after the last component stops using it.</p><p>This improves performance and reduces unnecessary requests.</p><h3>7. Tag-based invalidation</h3><p>A notifications example might use tags like this:</p><pre>addAdminNotification: builder.mutation({<br>  query: (data) =&gt; ({<br>    url: &quot;/notifications&quot;,<br>    method: &quot;POST&quot;,<br>    body: data,<br>  }),<br>  invalidatesTags: [&quot;Notifications&quot;],<br>}),</pre><p>And the corresponding query provides that tag:</p><pre>getAdminNotifications: builder.query({<br>  query: () =&gt; ({<br>    url: &quot;/notifications&quot;,<br>    method: &quot;GET&quot;,<br>  }),<br>  providesTags: [&quot;Notifications&quot;],<br>  keepUnusedDataFor: 60,<br>  transformResponse: (response) =&gt; response,<br>}),</pre><p>This is one of RTK Query’s most useful features.</p><p>Here is what happens:</p><ul><li>getAdminNotifications fetches notifications and marks the cache with the Notifications tag</li><li>addAdminNotification invalidates that tag after a successful mutation</li><li>RTK Query knows the notifications query is now stale</li><li>it automatically refetches the notifications</li></ul><p>That means you do not have to manually dispatch a second fetch action after a mutation.</p><h3>Why this approach is better than traditional Redux async patterns</h3><p>Traditional Redux async data flow often required several files:</p><ul><li>constants</li><li>actions</li><li>reducer</li><li>thunk</li></ul><p>For just one endpoint.</p><p>With RTK Query, most of that lives in one endpoint definition.</p><h3>Traditional style</h3><p>You might have needed:</p><ul><li>FETCH_PRODUCTS_REQUEST</li><li>FETCH_PRODUCTS_SUCCESS</li><li>FETCH_PRODUCTS_FAIL</li><li>action creators</li><li>reducer cases</li><li>thunk function</li><li>selector functions</li></ul><h3>RTK Query style</h3><p>You define:</p><pre>getProducts: builder.query({<br>  query: () =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;GET&quot;,<br>  }),<br>})</pre><p>And then consume:</p><pre>const { data, isLoading, error } = useGetProductsQuery();</pre><p>That is a massive simplification.</p><h3>Breaking down the file structurally</h3><p>An RTK Query file can usually be understood in layers.</p><h3>1. Feature grouping</h3><p>Although a file may be large, the endpoints are often grouped by business domain:</p><ul><li>product management</li><li>inventory</li><li>categories</li><li>coupons</li><li>customers</li><li>orders</li><li>notifications</li><li>payments</li></ul><p>That is good from a domain perspective, though the file may become big enough that splitting it improves maintainability.</p><h3>2. Endpoint style consistency</h3><p>Most endpoints follow a predictable structure:</p><pre>someMutation: builder.mutation({<br>  query: (data) =&gt; ({<br>    url: endpoint,<br>    method: &quot;POST&quot;,<br>    body: data,<br>  }),<br>}),</pre><p>or</p><pre>someQuery: builder.query({<br>  query: () =&gt; ({<br>    url: endpoint,<br>    method: &quot;GET&quot;,<br>  }),<br>}),</pre><p>That consistency is helpful for teams.</p><h3>3. Use of extraOptions</h3><p>Some endpoints may include:</p><pre>extraOptions: { serviceKey: &quot;billing&quot; },</pre><p>This suggests the app likely uses a custom baseQuery wrapper that routes some requests to a different backend service, probably billing or payment-related.</p><p>That means the architecture is not just RTK Query, but a customized RTK Query multi-service API layer.</p><p>This is a practical enterprise-style pattern.</p><h3>Likely architecture behind extraOptions: { serviceKey: &quot;billing&quot; }</h3><p>Although that code is not shown, the base query may look something like this conceptually:</p><pre>const dynamicBaseQuery = async (args, api, extraOptions) =&gt; {<br>  const serviceKey = extraOptions?.serviceKey;</pre><pre>  let baseUrl = MAIN_API_URL;</pre><pre>  if (serviceKey === &quot;billing&quot;) {<br>    baseUrl = BILLING_SERVICE_URL;<br>  }</pre><pre>  return fetchBaseQuery({ baseUrl })(args, api, extraOptions);<br>};</pre><p>This allows one RTK Query setup to speak to multiple backends.</p><p>That is a neat pattern when your app depends on:</p><ul><li>main application API</li><li>billing service</li><li>auth service</li><li>analytics service</li></ul><h3>How components use this setup</h3><p>A query hook is used like this:</p><pre>const { data, isLoading, error } = useGetOrdersQuery();</pre><p>A mutation hook is used like this:</p><pre>const [createCoupon, { isLoading, error }] = useCreateCouponMutation();</pre><pre>const handleCreate = async () =&gt; {<br>  try {<br>    const result = await createCoupon(payload).unwrap();<br>    console.log(result);<br>  } catch (err) {<br>    console.error(err);<br>  }<br>};</pre><p>The .unwrap() call is especially useful because it converts the mutation result into a standard promise:</p><ul><li>success resolves with raw response data</li><li>failure throws an error you can catch with try/catch</li></ul><p>That makes async form submission logic cleaner.</p><h3>Important strengths of RTK Query</h3><h4>1. Less boilerplate</h4><p>This is probably the biggest win.</p><h4>2. Built-in caching</h4><p>No need to manually store and reuse fetched data.</p><h4>3. Auto-generated hooks</h4><p>Cleaner React code.</p><h4>4. Automatic loading and error states</h4><p>No manual reducer flags needed for every request.</p><h4>5. Refetching and invalidation</h4><p>A huge help after create, update, or delete operations.</p><h4>6. Scales well</h4><p>Especially when using a base apiSlice and injectEndpoints.</p><h4>7. Good developer experience</h4><p>It is easier to read and maintain than older Redux async code.</p><h3>Limitations and trade-offs</h3><p>RTK Query is great, but not magic.</p><h4>1. Large files can get messy</h4><p>A large endpoint file can work fine, but once it grows too much, splitting it helps. You might separate things into:</p><ul><li>productApiSlice.js</li><li>orderApiSlice.js</li><li>couponApiSlice.js</li><li>notificationApiSlice.js</li></ul><p>All can still inject into the same apiSlice.</p><h4>2. Naming consistency matters a lot</h4><p>There can be naming issues that confuse future developers.</p><p>For example:</p><ul><li>getAdminNotifcations should probably be getAdminNotifications</li><li>comments saying DEPRECIATED should be deprecated</li></ul><p>Small issues, but they add friction over time.</p><h4>3. Tagging is often underused</h4><p>Sometimes only one area, such as notifications, uses invalidation properly. Many other mutation-query relationships could benefit from it.</p><p>For example:</p><ul><li>after creating a product, invalidate the product list</li><li>after deleting a coupon, invalidate coupons</li><li>after updating inventory, invalidate product stock data</li><li>after changing an order status, invalidate orders</li></ul><p>Without invalidation, components may show stale data until manually refetched.</p><h4>4. Response shapes can become inconsistent</h4><p>Some endpoints may return response, while others return response.data.</p><p>That can create inconsistency in the UI layer. A more uniform transform strategy makes the app easier to work with.</p><h3>Best practices for improving this codebase</h3><h4>1. Split the API file by domain</h4><p>Even if all files inject into the same base API, separating concerns helps a lot.</p><p>For example:</p><ul><li>productApi.js</li><li>orderApi.js</li><li>inventoryApi.js</li><li>paymentApi.js</li><li>notificationApi.js</li></ul><h4>2. Add tags for more entities</h4><p>Example:</p><pre>tagTypes: [&quot;Products&quot;, &quot;Orders&quot;, &quot;Coupons&quot;, &quot;Notifications&quot;]</pre><p>Then:</p><pre>getProducts: builder.query({<br>  query: () =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;GET&quot;,<br>  }),<br>  providesTags: [&quot;Products&quot;],<br>}),</pre><p>And:</p><pre>createProduct: builder.mutation({<br>  query: (data) =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;POST&quot;,<br>    body: data,<br>  }),<br>  invalidatesTags: [&quot;Products&quot;],<br>}),</pre><p>That keeps data fresh automatically.</p><h4>3. Standardize response transformation</h4><p>Choose one pattern:</p><ul><li>either always return raw backend response</li><li>or always transform to the useful payload</li></ul><p>Most teams prefer transforming at the API layer so components stay simple.</p><h4>4. Use clearer endpoint names</h4><p>For example:</p><ul><li>getAdminNotifcations → getAdminNotifications</li><li>createStoreDiscount might be clearer than addDiscount</li><li>getProductBySlug might be clearer than getSingleProduct</li></ul><p>Cleaner names make the file easier to scan.</p><h4>5. Consider TypeScript if the project allows it</h4><p>RTK Query becomes even stronger with TypeScript because endpoint args and responses are typed.</p><p>Example:</p><pre>getProducts: builder.query&lt;Product[], void&gt;({<br>  query: () =&gt; ({<br>    url: &quot;/products&quot;,<br>    method: &quot;GET&quot;,<br>  }),<br>}),</pre><p>That improves autocomplete and catches mistakes earlier.</p><h3>RTK Query vs Redux Thunk</h3><p>A lot of people ask whether RTK Query replaces Redux Thunk entirely.</p><p>Not always.</p><p>RTK Query is best for:</p><ul><li>API requests</li><li>caching server responses</li><li>syncing remote data</li></ul><p>Redux Thunk is still useful for:</p><ul><li>complex client-side orchestration</li><li>multi-step workflows not centered around API caching</li><li>local side effects and custom business logic</li></ul><p>That said, for most CRUD-style backend communication, RTK Query is usually the better fit.</p><h3>RTK Query vs React Query</h3><p>Another common comparison is RTK Query vs React Query.</p><p>Both solve server-state problems well.</p><h3>RTK Query</h3><p>Best when:</p><ul><li>your app already uses Redux</li><li>you want API state inside Redux</li><li>you like centralized endpoint definitions</li><li>you want Redux DevTools visibility</li></ul><h3>React Query</h3><p>Best when:</p><ul><li>your app does not use Redux</li><li>you want a library focused purely on server state</li><li>you prefer a hooks-first data fetching model without Redux coupling</li></ul><p>If your application already uses Redux, RTK Query is a very logical choice.</p><h3>What this architecture says about the app</h3><p>A well-structured RTK Query file tells us a lot about the application design.</p><p>It suggests:</p><ul><li>the app uses Redux Toolkit</li><li>server communication is centralized</li><li>the backend has many domain-specific endpoints</li><li>payment logic may use a separate service</li><li>React components consume data through generated hooks</li><li>some areas already use tag-based refetching</li><li>the codebase is reasonably mature and feature-rich</li></ul><p>This is a modern Redux architecture, even if there is room to improve naming, tagging, and file organization.</p><h3>A simplified mental model of RTK Query</h3><p>You can think of RTK Query like this:</p><ul><li>createApi creates the API engine</li><li>injectEndpoints adds features to that engine</li><li>builder.query defines reads</li><li>builder.mutation defines writes</li><li>hooks are auto-generated for React</li><li>cache is handled automatically</li><li>tags keep stale data in sync</li></ul><p>That is really the core of it.</p><h3>Example: converting old Redux logic to RTK Query</h3><p>Old style:</p><pre>dispatch(fetchProductsStart());<br>try {<br>  const response = await axios.get(&quot;/products&quot;);<br>  dispatch(fetchProductsSuccess(response.data));<br>} catch (error) {<br>  dispatch(fetchProductsFail(error));<br>}</pre><p>RTK Query style:</p><pre>getProducts: builder.query({<br>  query: () =&gt; &quot;/products&quot;,<br>});</pre><p>Then in a component:</p><pre>const { data, isLoading, error } = useGetProductsQuery();</pre><p>Much cleaner. Much less repetition.</p><h3>Final conclusion</h3><p>The approach shown here is <strong>Redux Toolkit Query (RTK Query)</strong>, which is the modern Redux approach for managing API calls and server-side state.</p><p>It replaces a lot of traditional Redux boilerplate by giving you:</p><ul><li>centralized endpoint definitions</li><li>built-in caching</li><li>automatic loading and error handling</li><li>generated React hooks</li><li>cache invalidation support</li><li>cleaner and more scalable async data flow</li></ul><p>This implementation specifically uses:</p><ul><li>a base API slice</li><li>injected endpoints</li><li>queries for reads</li><li>mutations for writes</li><li>custom extra options for multi-service routing</li><li>tag-based invalidation where needed</li></ul><p>So this is best described as a <strong>feature-based RTK Query API slice architecture in Redux Toolkit</strong>.</p><p>It is a strong and modern approach, especially for applications with lots of backend interaction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1066f94d1a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring {exec} in Node.js]]></title>
            <link>https://medium.com/@ralphbetta/exploring-exec-in-node-js-db13ff5c6593?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/db13ff5c6593</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[shell-script]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 14:27:34 GMT</pubDate>
            <atom:updated>2025-03-20T14:27:34.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sdcdybycDKYL6fuuhNDKg.jpeg" /></figure><p>The exec function in Node.js, from the child_process module, allows you to execute system commands from your JavaScript code. This is particularly useful for running shell commands, interacting with APIs using cURL, executing scripts, managing processes, and working with databases.</p><h3>Importing exec</h3><p>To use exec, you first need to require it from the child_process module:</p><pre>const { exec } = require(&#39;child_process&#39;);</pre><h3>Common Use Cases for exec</h3><h3>1. Calling External APIs with cURL</h3><p>Instead of using axios or fetch, you can make HTTP requests using cURL via exec:</p><pre>exec(&#39;curl -s https://api.example.com/data&#39;, (error, stdout, stderr) =&gt; {<br>  if (error) {<br>    console.error(`Error: ${error.message}`);<br>    return;<br>  }<br>  console.log(stdout); // API response<br>});</pre><h3>2. Executing Shell Commands</h3><p>You can run system commands like listing files:</p><h4>On Linux/macOS:</h4><pre>exec(&#39;ls&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h4>On Windows:</h4><pre>exec(&#39;dir&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h3>3. Running Bash Scripts</h3><p>If you have a bash script that automates a task, you can execute it from Node.js:</p><pre>exec(&#39;sh ./myscript.sh&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h3>4. Interacting with Git</h3><p>You can automate Git commands like pulling the latest code:</p><pre>exec(&#39;git pull origin main&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h3>5. Managing System Processes</h3><p>If you’re using process managers like PM2, you can restart your app via exec:</p><pre>exec(&#39;pm2 restart my-app&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h3>6. Running Database Commands</h3><p>You can execute database queries directly from the command line:</p><h4>MySQL Example:</h4><pre>exec(&#39;mysql -u root -p mydatabase -e &quot;SELECT * FROM users;&quot;&#39;, (error, stdout, stderr) =&gt; {<br>  console.log(stdout);<br>});</pre><h3>Handling Errors in exec</h3><p>It’s important to handle errors properly when using exec. The callback function provides three parameters:</p><ul><li>error: Contains error details if the command fails.</li><li>stdout: Captures standard output (command result).</li><li>stderr: Captures standard error output.</li></ul><p>Example:</p><pre>exec(&#39;invalid_command&#39;, (error, stdout, stderr) =&gt; {<br>  if (error) {<br>    console.error(`Error: ${error.message}`);<br>    return;<br>  }<br>  if (stderr) {<br>    console.error(`stderr: ${stderr}`);<br>    return;<br>  }<br>  console.log(stdout);<br>});</pre><h3>Best Practices for exec</h3><ol><li><strong>Sanitize Input:</strong> Avoid shell injection vulnerabilities by validating user input before passing it to exec.</li><li><strong>Use Absolute Paths:</strong> When running scripts, use absolute file paths to avoid unexpected errors.</li><li><strong>Limit Output Buffer:</strong> Since exec buffers output in memory, be cautious with large outputs.</li><li><strong>Consider Security Risks:</strong> Be mindful of executing commands that could compromise system security.</li></ol><h3>exec vs spawn: Choosing the Right Method</h3><p>While exec is useful for quick commands, it buffers all output in memory. For handling large outputs or streaming data, spawn is a better alternative.</p><p>FeatureexecspawnBufferingStores all output in memoryStreams output in real-timePerformanceSuitable for small outputsBetter for large outputsUse CaseSimple commands, API callsLong-running processes</p><h3>Example of spawn</h3><pre>const { spawn } = require(&#39;child_process&#39;);<br>const ls = spawn(&#39;ls&#39;, [&#39;-lh&#39;]);</pre><pre>ls.stdout.on(&#39;data&#39;, (data) =&gt; {<br>  console.log(`Output: ${data}`);<br>});</pre><pre>ls.stderr.on(&#39;data&#39;, (data) =&gt; {<br>  console.error(`Error: ${data}`);<br>});</pre><h3>Conclusion</h3><p>Using exec in Node.js allows for seamless interaction with the operating system, automating tasks, and integrating with external tools. However, for handling large data streams, spawn is a better choice. By understanding these execution methods, you can optimize your application&#39;s performance and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db13ff5c6593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Smart Contract Creation]]></title>
            <link>https://medium.com/@ralphbetta/dynamic-smart-contract-creation-42347a8fd44c?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/42347a8fd44c</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3-development]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[remix]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 12:53:17 GMT</pubDate>
            <atom:updated>2024-12-28T12:53:17.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQ1QrRWspUU7yK9Q2RySvw.jpeg" /></figure><p>In the blockchain world, creating a smart contract from another smart contract is a powerful and versatile feature. This approach enhances modularity, scalability, and adaptability, enabling developers to build dynamic, efficient, and decentralized systems. Whether you’re building token factories, decentralized marketplaces, or upgradable systems, understanding this concept is key to unlocking blockchain’s full potential.</p><h3>Why Create Contracts from Other Contracts?</h3><h4>1. Dynamic Deployment</h4><p>Creating contracts at runtime allows systems to adapt to changing requirements. This is particularly useful in decentralized applications where new functionality or entities need to be added dynamically.</p><h4>2. Factory Pattern</h4><p>The Factory pattern simplifies contract management by centralizing the creation process. This ensures consistency and makes it easier to track and interact with deployed instances.</p><h4>3. Modularity and Reusability</h4><p>Instead of duplicating logic, developers can deploy reusable base contracts multiple times. This reduces development overhead and ensures uniform behavior across instances.</p><h4>4. Customization</h4><p>Parent contracts can create child contracts with specific parameters, allowing for tailored behavior in each instance.</p><h4>5. Access Control</h4><p>Parent contracts can maintain a registry of deployed child contracts, enabling controlled access and better management of deployed instances.</p><h4>6. Gas Optimization</h4><p>Techniques like deploying minimal proxy contracts significantly reduce deployment costs, making the system more efficient.</p><h4>7. Upgradability</h4><p>Child contracts can act as replaceable modules, allowing for system updates without affecting the entire ecosystem.</p><h3>Use Cases for Contract Creation</h3><h4>1. Token Factories</h4><p><strong>Scenario:</strong> A platform allows users to create their own ERC20 tokens on demand.</p><p><strong>Code Example:</strong></p><pre>pragma solidity ^0.8.0;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract TokenFactory {<br>    address[] public tokens;<br><br>    function createToken(string memory name, string memory symbol) public {<br>        ERC20 newToken = new ERC20(name, symbol);<br>        tokens.push(address(newToken));<br>    }<br>}</pre><h4>2. DeFi Platforms (Liquidity Pools)</h4><p><strong>Scenario:</strong> A decentralized exchange deploys new liquidity pool contracts for each trading pair.</p><p><strong>Example:</strong> Uniswap uses factory contracts to manage pool deployment.</p><h4>3. NFT Marketplaces</h4><p><strong>Scenario:</strong> An NFT platform allows creators to deploy unique contracts for their collections.</p><p><strong>Code Example:</strong></p><pre>pragma solidity ^0.8.0;<br><br>import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;;<br><br>contract NFTFactory {<br>    address[] public nftCollections;<br><br>    function createCollection(string memory name, string memory symbol) public {<br>        ERC721 newCollection = new ERC721(name, symbol);<br>        nftCollections.push(address(newCollection));<br>    }<br>}</pre><h4>4. DAO Systems</h4><p><strong>Scenario:</strong> A DAO platform deploys contracts for each community with tailored governance rules.</p><p><strong>Example:</strong> Aragon DAOs use factories to spawn customized DAOs.</p><h4>5. Escrow Contracts</h4><p><strong>Scenario:</strong> A marketplace creates individual escrow contracts for secure transactions.</p><p><strong>Code Example:</strong></p><pre>pragma solidity ^0.8.0;<br><br>contract Escrow {<br>    address public buyer;<br>    address public seller;<br>    uint public amount;<br><br>    constructor(address _buyer, address _seller, uint _amount) {<br>        buyer = _buyer;<br>        seller = _seller;<br>        amount = _amount;<br>    }<br>}<br><br>contract EscrowFactory {<br>    Escrow[] public escrows;<br><br>    function createEscrow(address buyer, address seller, uint amount) public {<br>        Escrow newEscrow = new Escrow(buyer, seller, amount);<br>        escrows.push(newEscrow);<br>    }<br>}</pre><h4>6. Multi-Signature Wallets</h4><p><strong>Scenario:</strong> A platform deploys unique wallets for groups requiring shared fund control.</p><h3>Security Considerations</h3><p>When creating contracts from other contracts, developers should:</p><ol><li><strong>Ensure Proper Initialization:</strong> Misconfigured child contracts can lead to vulnerabilities.</li><li><strong>Account for Gas Limits:</strong> Contract creation can be resource-intensive.</li><li><strong>Restrict Access:</strong> Prevent unauthorized creation of contracts to avoid misuse or spam.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42347a8fd44c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Environment Configuration in]]></title>
            <link>https://medium.com/@ralphbetta/environment-configuration-in-d11b4a8c5f52?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/d11b4a8c5f52</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 14:02:54 GMT</pubDate>
            <atom:updated>2024-12-17T14:02:54.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ssP7p30SUVqmj0kQi_UvQ.jpeg" /></figure><blockquote><strong>Flutter using </strong><strong>.env vs. </strong><strong>--dart-define</strong></blockquote><p>Managing environment-specific variables is crucial in software development to keep sensitive configurations (like API keys, URLs, or tokens) secure and manageable. In Flutter, developers often use two common approaches for environment management:</p><ol><li><strong>.env files</strong> (via third-party packages like flutter_dotenv)</li><li><strong>--dart-define</strong> (built-in Dart/Flutter functionality)</li></ol><p>This article will cover the <strong>differences</strong>, <strong>importance</strong>, and when to use each approach.</p><h3>1. Overview</h3><blockquote><strong>Feature:</strong></blockquote><p><strong>.env Files: </strong>Uses a local .env file for storing key-value pairs.</p><p><strong>— dart-define: </strong>Passes key-value pairs via Flutter CLI at build/run time.</p><blockquote><strong>Tool/Package:</strong></blockquote><p><strong>.env Files: </strong>Requires a package like flutter_dotenv.</p><p><strong>— dart-define: </strong>Built-in feature of Flutter.</p><blockquote><strong>Flexibility:</strong></blockquote><p><strong>.env Files: </strong>Easy to manage during development.</p><p><strong>— dart-define: </strong>Best for CI/CD pipelines and production builds.</p><blockquote><strong>Security:</strong></blockquote><p><strong>.env Files:</strong> files can be mistakenly included in version control.</p><p><strong>— dart-define: </strong>Variables are baked into the build; not included in source files.</p><h3>2. Understanding .env Files</h3><h3>What are .env Files?</h3><p>.env files store environment-specific variables (e.g., API URLs, tokens) as plain text in the form of KEY=VALUE. These files are <strong>not part of the source code</strong> and must be loaded during runtime.</p><p>In Flutter, you typically use the flutter_dotenv package to manage .env files.</p><h3>Setup Using flutter_dotenv</h3><ol><li><strong>Install the package:</strong></li></ol><pre>dependencies:<br>  flutter_dotenv: ^5.1.0</pre><p><strong>2. Create a </strong><strong>.env file</strong>:</p><pre>API_URL=https://dev.site.com<br>API_KEY=#</pre><p><strong>3. Load the </strong><strong>.env file</strong> in your code:</p><pre>import &#39;package:flutter_dotenv/flutter_dotenv.dart&#39;;<br><br>void main() async {<br>  await dotenv.load(fileName: &quot;.env&quot;);<br>  runApp(MyApp());<br>}<br><br>String apiUrl = dotenv.env[&#39;API_URL&#39;] ?? &#39;https://default.url&#39;;</pre><p><strong>4. Add to the list of your assets</strong></p><pre>- .env</pre><p><strong>5. Add </strong><strong>.env to </strong><strong>.gitignore</strong>:</p><pre>.env</pre><ul><li>Pros of .env Files</li><li>Easy to set up and manage for <strong>local development</strong>.</li><li>Can have multiple .env files (e.g., .env.dev, .env.prod) for different environments.</li><li>Works well with projects where no CI/CD is configured.</li></ul><h3>Cons of .env Files</h3><ul><li><strong>Not secure</strong>: If mistakenly checked into version control, sensitive data could be exposed.</li><li>Requires an additional package.</li><li>Does not work well with Flutter Web because assets must be bundled into the build.</li></ul><h3>3. Understanding --dart-define</h3><h3>What is --dart-define?</h3><p>--dart-define is a Flutter build/run argument that allows you to pass environment-specific variables <strong>at compile time</strong>. These variables are baked directly into the compiled code.</p><h3>How to Use --dart-define</h3><ol><li><strong>Pass Variables at Build Time</strong>:</li></ol><pre>flutter run --dart-define=API_URL=https://https://dev.url --dart-define=API_KEY=devKey</pre><p>2. <strong>Access Variables in Your Code</strong>:</p><pre>const apiUrl = String.fromEnvironment(&#39;API_URL&#39;, defaultValue: &#39;https://default.url&#39;);<br>const apiKey = String.fromEnvironment(&#39;API_KEY&#39;, defaultValue: &#39;default_key&#39;);</pre><p><strong>3. Production Example</strong> (CI/CD):</p><pre>flutter build web --release --dart-define=API_URL=https://dev.site.com --dart-define=API_KEY=devKey123</pre><h3>Pros of --dart-define</h3><ul><li><strong>Secure for production builds</strong>: Environment variables are passed only at build time.</li><li>No additional packages required (built into Flutter).</li><li>Works seamlessly with <strong>Flutter Web</strong> and CI/CD pipelines.</li><li>Avoids hardcoding sensitive information into the source code.</li></ul><h3>Cons of --dart-define</h3><ul><li>Not as convenient for local development when switching environments frequently.</li><li>Requires explicit CLI flags, which can be cumbersome.</li><li>No ability to load multiple .env files dynamically.</li></ul><h3>4. Key Differences</h3><blockquote><strong>Aspect:</strong></blockquote><p><strong>.env Files: </strong>Loaded at runtime.</p><p><strong>— dart-define: </strong>Passed at compile time during build.</p><blockquote><strong>Ease of Use:</strong></blockquote><p><strong>.env Files: </strong>Easier for local development.</p><p><strong>— dart-define:</strong> suitable for automated builds in CI/CD.</p><blockquote><strong>Security:</strong></blockquote><p><strong>.env Files: </strong>Potential risk if checked into version control.</p><p><strong>— dart-define: </strong>More secure: values are part of the compiled app.</p><blockquote><strong>Flutter Web:</strong></blockquote><p><strong>.env Files: </strong>Requires manual asset inclusion.</p><p><strong>— dart-define: </strong>Works natively with Flutter Web builds.</p><blockquote><strong>Package Needed:</strong></blockquote><ul><li><strong>.env Files: </strong>Requires flutter_dotenv.</li><li><strong>— dart-define: </strong>No additional packages are needed.</li></ul><h3>5. When to Use Each?</h3><h4>Use .env Files When:</h4><ul><li>Working in <strong>local development</strong> or small teams.</li><li>You need quick environment switching without rebuilding.</li><li>Managing dynamic configurations that need to be loaded at runtime.</li></ul><h4>Use --dart-define When:</h4><ul><li>Building for <strong>production</strong> or CI/CD pipelines.</li><li>Deploying <strong>Flutter Web</strong>, as .env doesn’t work well with it.</li><li>Security is a concern, and you want to avoid storing sensitive keys in plain files.</li><li>You need environment variables baked into the compiled code.</li></ul><h3>6. Best Practices</h3><ol><li><strong>For Local Development</strong>:</li></ol><ul><li>Use .env files with flutter_dotenv for convenience.</li><li>Add .env to .gitignore to prevent accidental commits.</li></ul><p><strong>2. For Production Builds</strong>:</p><ul><li>Use --dart-define to securely inject environment variables.</li><li>Avoid hardcoding secrets directly into the source code.</li></ul><p><strong>3. Consistent Code</strong>: Use String.fromEnvironment in your codebase to handle both methods seamlessly:</p><pre>const apiUrl = String.fromEnvironment(&#39;API_URL&#39;, defaultValue: &#39;https://default.url&#39;);</pre><p>Both .env files and --dart-define are valuable tools for managing environment-specific variables in Flutter. While .env is great for local development, --dart-define is better suited for production builds and CI/CD pipelines, especially with Flutter Web.</p><p>By understanding the differences and when to use each, you can create a secure, scalable, and flexible environment configuration for your Flutter projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d11b4a8c5f52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Multiple Node.js Versions Within Your System]]></title>
            <link>https://medium.com/@ralphbetta/managing-multiple-node-js-versions-within-your-system-7e09ac16361e?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e09ac16361e</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nvm]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 05:58:04 GMT</pubDate>
            <atom:updated>2024-12-17T05:58:04.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Managing Multiple Node.js Versions in Your System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTfQnYEPqrkTAHIKmZAaCA.jpeg" /></figure><p>As a developer working with Node.js, you may encounter projects that require different versions of Node.js. Managing these versions manually can be cumbersome, but tools exist to streamline this process and allow seamless switching between versions. In this article, we will explore how to manage multiple Node.js versions effectively on your system.</p><h3>Why Manage Multiple Node.js Versions?</h3><ul><li>Different projects may depend on different Node.js versions.</li><li>Avoid breaking dependencies or encountering compatibility issues.</li><li>Test your applications on various versions of Node.js.</li><li>Stay up-to-date with the latest features while supporting older projects.</li></ul><h3>Popular Tools for Managing Node.js Versions</h3><h3>1. Node Version Manager (NVM)</h3><p>NVM is the most popular tool for managing Node.js versions. It allows you to install, switch, and manage different versions of Node.js easily.</p><h4>Install NVM</h4><p>To install NVM on a Unix-based system (Linux/macOS), run the following command in your terminal:</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash</pre><p>For Windows users, NVM for Windows is a separate tool. You can download the installer from <a href="https://github.com/coreybutler/nvm-windows">nvm-windows GitHub</a>.</p><p>After installation, restart your terminal and verify NVM is installed:</p><pre>nvm --version</pre><h4>Install and Use Node.js with NVM</h4><p>With NVM, you can install any Node.js version. For example:</p><pre>nvm install 16.20.0   # Install Node.js version 16.20.0<br>nvm install 18.17.0   # Install Node.js version 18.17.0</pre><p>To switch between versions, use:</p><pre>nvm use 16.20.0</pre><p>You can set a default version using:</p><pre>nvm alias default 18.17.0</pre><p>To list all installed versions:</p><pre>nvm ls</pre><h3>2. n (Node Version Management)</h3><p>n is another tool for managing Node.js versions. It is lightweight and can be installed using npm.</p><h4>Install n</h4><p>Run the following command to install n globally:</p><pre>npm install -g n</pre><h4>Install and Switch Node.js Versions</h4><p>To install a specific Node.js version, use:</p><pre>sudo n 16.20.0<br>sudo n 18.17.0</pre><p>Switch between installed versions:</p><pre>sudo n 16.20.0</pre><p>You can also use n latest to install the latest Node.js version or n lts for the latest Long-Term Support version.</p><h3>3. Volta</h3><p>Volta is a fast and reliable tool for managing Node.js versions. It ensures consistency across projects.</p><h4>Install Volta</h4><p>Run the following command to install Volta:</p><pre>curl https://get.volta.sh | bash</pre><p>After installation, restart your terminal and verify Volta:</p><pre>volta --version</pre><h4>Manage Node.js with Volta</h4><p>Install a specific Node.js version using:</p><pre>volta install node@18.17.0</pre><p>Switch between versions seamlessly without additional commands since Volta automatically manages versions per project.</p><h3>4. Using Docker for Node.js Version Management</h3><p>Docker is a containerization tool that allows you to run isolated environments for different Node.js versions.</p><h4>Run Node.js in a Docker Container</h4><p>To use Node.js version 18 in a Docker container, create a Dockerfile with the following content:</p><pre>FROM node:18<br>WORKDIR /app<br>COPY . .<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><p>Build and run the container:</p><pre>docker build -t node-app .<br>docker run -p 3000:3000 node-app</pre><p>Using Docker, you can isolate Node.js environments without affecting your local setup.</p><h3>Best Practices for Managing Node.js Versions</h3><ol><li><strong>Set a Node.js version per project</strong>: Use tools like NVM or Volta to specify Node.js versions per project using package.json engines field.</li><li><strong>Stay organized</strong>: Avoid clutter by uninstalling unused versions with nvm uninstall or equivalent commands.</li><li><strong>Automate switching</strong>: Use tools like nvm use and shell scripts to switch Node.js versions automatically when entering a project directory.</li></ol><p>Managing multiple Node.js versions is crucial for modern development workflows, especially when handling various projects or dependencies. Tools like NVM, n, Volta, and Docker make this process simple and efficient.</p><p>By adopting one of these tools, you can streamline Node.js version management, avoid conflicts, and ensure consistency across your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e09ac16361e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Postgress Database for Local and Remote Access]]></title>
            <link>https://medium.com/@ralphbetta/setting-up-postgress-database-for-local-and-remote-access-8f81fb45ad5b?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f81fb45ad5b</guid>
            <category><![CDATA[vps]]></category>
            <category><![CDATA[psql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 21:17:56 GMT</pubDate>
            <atom:updated>2024-12-07T21:17:56.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRFpLmvqnFDrycss8qgdWg.jpeg" /></figure><p>Comprehensive Guide to Setting Up PostgreSQL on Ubuntu Using Local Repository</p><h3>Step 1: Install PostgreSQL</h3><ol><li><strong>Update the package list</strong>: Ensure your local package list is up-to-date.</li></ol><pre>sudo apt-get update</pre><p>2. <strong>Display PostgreSQL package details (optional)</strong>: This step provides information about the PostgreSQL package.</p><pre>sudo apt show postgresql</pre><p>3. <strong>Install PostgreSQL and its additional components</strong>: Install the main PostgreSQL server and optional contributed utilities.</p><pre>sudo apt install postgresql postgresql-contrib</pre><p>4. <strong>Verify the installation</strong>: Access PostgreSQL and check its version.</p><pre>sudo -u postgres psql<br>SELECT version();<br>\q</pre><h3>Step 2: Check PostgreSQL Service Status</h3><ol><li><strong>Check if the PostgreSQL service is active</strong>: Confirm the service is running using the systemctl command.</li></ol><pre>sudo service postgresql status #OR<br><br>sudo systemctl status postgresql</pre><p>2. <strong>Verify PostgreSQL readiness</strong>: Use the pg_isready command to ensure PostgreSQL is ready to accept connections.</p><pre>sudo pg_isready</pre><h3>Step 3: Change PostgreSQL User Password</h3><ol><li><strong>Access PostgreSQL</strong>: Use the postgres superuser to log in.</li></ol><pre>sudo -u postgres psql</pre><p>2. <strong>Set a new password for the </strong><strong>postgres user</strong>:</p><pre>ALTER USER postgres PASSWORD &#39;NewPassword&#39;;<br>\p<br>\q</pre><p>3. <strong>Restart PostgreSQL to apply changes</strong>: Restart the service for changes to take effect.</p><pre>sudo service postgresql restart</pre><h3><strong>Step 4: Create a Database and User</strong></h3><ol><li>Access the PostgreSQL interface:</li></ol><pre>sudo -u postgres psql</pre><p>2. Create a database and user:</p><pre>CREATE DATABASE mydatabase;<br>CREATE USER myuser WITH PASSWORD &#39;mypassword&#39;;<br>GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;</pre><p>3. <strong>(Optional) Assign additional roles to the user</strong>: Enable the user to create databases or grant superuser privileges.</p><pre>ALTER ROLE myuser CREATEDB;<br>ALTER ROLE myuser SUPERUSER;</pre><p>4. List all users to confirm and exit PSQL interface:</p><pre>\du<br>\q</pre><p>5. Connect to the database as the new user:</p><pre>psql -U myuser -d mydatabase</pre><h3>Grant Specific Permissions</h3><ol><li>Grant `CONNECT` privilege only:</li></ol><pre>GRANT CONNECT ON DATABASE mydatabase TO myuser;</pre><h3>Step 5: Backup and Restore</h3><ol><li><strong>Backup a database</strong>: Create a backup of the specified database using pg_dump.</li></ol><pre>pg_dump -U postgres mydatabase &gt; mydatabase.sql</pre><p>2. <strong>Restore a database</strong>: Use the psql command to restore a database from a backup file.</p><pre>psql -U postgres -d mydatabase &lt; mydatabase.sql</pre><h3>Step 6: Configure PostgreSQL for Remote Access</h3><ol><li><strong>Edit the PostgreSQL configuration file</strong>: Allow remote connections by modifying postgresql.conf.</li></ol><pre>sudo nano /etc/postgresql/16/main/postgresql.conf</pre><p>2. Locate and modify the following line:</p><pre>#listen_addresses = &#39;localhost&#39;</pre><p>Uncomment and change it to:</p><pre>listen_addresses = &#39;*&#39;</pre><p>3. <strong>Edit the </strong><strong>pg_hba.conf file</strong>: Add a new rule to allow remote connections.</p><pre>sudo nano /etc/postgresql/16/main/pg_hba.conf</pre><p>4. Add the following line to allow all IPs with MD5 authentication:</p><pre>host    all             all             0.0.0.0/0               md5</pre><p>5. <strong>Restart PostgreSQL</strong>: Apply the changes by restarting the service.</p><pre>sudo systemctl restart postgresql</pre><h3>Step 7: Configure Firewall for Remote Access</h3><p>1. <strong>Allow port 5432 for TCP connections</strong>: Open the port used by PostgreSQL for remote access.</p><pre>sudo ufw allow 5432/tcp</pre><h3>Step 8: Connect to PostgreSQL Remotely</h3><p><strong>Connect to PostgreSQL from a remote machine</strong>: Use the psql command with the host&#39;s IP address.</p><pre>psql -h &lt;ip_address&gt; -p 5432 -d &lt;database&gt; -U &lt;username&gt;</pre><p>Examples:</p><pre>psql -h localhost -p 5432 -d mydatabase -U myuser<br>psql -h 192.xxx.18.1 -p 5432 -d mydatabase -U myuser</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f81fb45ad5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up MySQL Database for Local and Remote Access]]></title>
            <link>https://medium.com/@ralphbetta/setting-up-mysql-database-for-local-and-remote-access-62379fe58aa3?source=rss-e11d2b567227------2</link>
            <guid isPermaLink="false">https://medium.com/p/62379fe58aa3</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[storage-solutions]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-management]]></category>
            <dc:creator><![CDATA[Ralphbetta]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 18:08:13 GMT</pubDate>
            <atom:updated>2024-12-07T18:08:13.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xpkmT6R8NcMsMhcP7PNsA.jpeg" /></figure><p>This tutorial covers the steps for setting up MySQL, creating databases, managing users, and configuring access on a VPS server. By the end of this guide, you will have a working MySQL environment with appropriate user permissions for both local and remote access.</p><h3>Prerequisites:</h3><ul><li>A VPS server running a Linux distribution (Ubuntu, CentOS, etc.).</li><li>A user with sudo privileges.</li><li>MySQL installed on the server (either mysql-server or mariadb-server depending on your setup).</li></ul><h3>Step 1: Install MySQL Server on VPS</h3><p>If MySQL is not already installed on your VPS, you can install it using the following commands based on your server’s OS:</p><h3>On Ubuntu/Debian:</h3><pre>sudo apt update<br>sudo apt install mysql-server</pre><h3>On CentOS/RHEL:</h3><pre>sudo yum install mysql-server<br>sudo systemctl start mysqld</pre><h3>On Fedora:</h3><pre>sudo dnf install mysql-server<br>sudo systemctl start mysqld</pre><p>Once the installation is complete, you should verify that the MySQL service is running:</p><pre>sudo systemctl status mysql</pre><h3>Step 2: Log in to MySQL as Root</h3><p>To start managing MySQL, log in as the root user:</p><pre>sudo mysql -u root -p</pre><p>You will be prompted for the root password you set earlier. After entering it, you’ll be logged into the MySQL shell.</p><h3>Step 3: List All Databases</h3><p>To view all the databases currently available on your MySQL server, run the following command:</p><pre>SHOW DATABASES;</pre><p>This will display a list of databases. If you’re just starting out, it might show only the default databases such as information_schema, mysql, and performance_schema.</p><h3>Step 4: Create a New Database</h3><p>To create a new database, use the following command:</p><pre>CREATE DATABASE dbname;</pre><p>You can replace pdatabase with the name you want for your new database. You can verify the creation by running SHOW DATABASES; again.</p><h3>Step 5: Create a New User</h3><p>Creating a new MySQL user requires specifying the username and the password. Here’s the syntax to create a user:</p><pre>CREATE USER &#39;dbuser&#39;@&#39;%&#39; IDENTIFIED BY &#39;dbpass&#39;;</pre><ul><li>&#39;puser&#39; is the name of the new user.</li><li>&#39;%&#39; is the host part. The % symbol means the user can log in from any host (i.e., remote access is allowed). You can restrict the user to a specific IP or range by replacing % it with an IP address, such as &#39;192..1.100&#39;.</li></ul><p>If you want to restrict access to a particular IP address or range:</p><pre>CREATE USER &#39;dbuser&#39;@&#39;192.xxx.1.100&#39; IDENTIFIED BY &#39;dbpass&#39;;</pre><h3>Password Policy:</h3><ul><li>Replace dbpass with a strong password for your user.</li><li>Ensure the password follows your organization’s password policy, e.g., at least 12 characters, a mix of upper and lower case, numbers, and special characters.</li></ul><h3>Step 6: Grant Privileges to the New User</h3><p>After creating the user, you need to assign permissions (privileges) to the user for accessing and modifying the database. You can either grant privileges for a specific database or globally across all databases.</p><h3>Granting Privileges on a Specific Database:</h3><p>To allow the user to have all privileges on the newly created pdatabase, run:</p><pre>GRANT ALL PRIVILEGES ON pdatabase.* TO &#39;dbuser&#39;@&#39;%&#39;;</pre><p>This gives the user full access (create, read, update, delete, etc.) to the pdatabase database.</p><h3>Granting Privileges on All Databases:</h3><p>To allow the user to have access to all databases:</p><pre>GRANT ALL PRIVILEGES ON *.* TO &#39;dbuser&#39;@&#39;%&#39; WITH GRANT OPTION;</pre><ul><li>*.* means all databases and all tables.</li><li>The WITH GRANT OPTION gives the user the ability to grant privileges to other users (use this carefully).</li></ul><h3>Limiting Access to Specific IP or Subnet:</h3><p>To restrict the user to a specific IP or range, for example, 192.168.1.100:</p><pre>GRANT ALL PRIVILEGES ON *.* TO &#39;dbuser&#39;@&#39;server_ip&#39; IDENTIFIED BY &#39;dbpass&#39;;</pre><h3>Step 7: Apply Changes</h3><p>To ensure the changes take effect, run the following command:</p><pre>FLUSH PRIVILEGES;</pre><p>This reloads the privileges table so that the changes are applied immediately.</p><h3>Step 8: Show User Privileges</h3><p>To verify the privileges granted to a specific user, you can use the following command:</p><pre>SHOW GRANTS FOR &#39;puser&#39;@&#39;%&#39;;</pre><p>This will display the privileges of the dbuser.</p><h3>Step 9: Test User Access</h3><p>To test if the new user can log in and perform actions, log out of the MySQL root user:</p><pre>EXIT;</pre><p>Then, log in as the new user:</p><pre>mysql -u puser -p</pre><p>You will be prompted for the password. Once logged in, you can try to access the pdatabase database:</p><pre>USE pdatabase;</pre><p>You can also check if the user can list tables, create new ones, etc. If any permissions are missing, you can adjust them by running GRANT again.</p><h3>Step 10: Allow Remote Access (Optional)</h3><p>If you need the MySQL server to be accessible remotely (from another machine), you may need to modify the MySQL configuration file.</p><ul><li><strong>Edit the MySQL Configuration:</strong></li></ul><p>Open the MySQL configuration file (this path might differ depending on your system):</p><pre>sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf   # On Ubuntu/Debian<br>sudo nano /etc/my.cnf                          # On CentOS/RHEL</pre><p>Look for the bind-address directive and change its value to 0.0.0.0 to allow MySQL to accept connections from any IP:</p><pre>bind-address = 0.0.0.0</pre><ul><li><strong>Restart MySQL:</strong></li></ul><p>After saving the file, restart MySQL to apply the changes:</p><pre>sudo systemctl restart mysql</pre><ul><li><strong>Allow MySQL Port in Firewall:</strong></li></ul><p>If your server has a firewall enabled, ensure that port 3306 (default MySQL port) is open for remote access:</p><pre>sudo ufw allow 3306</pre><p>Or for a more restrictive approach, only allow connections from specific IP addresses:</p><pre>sudo ufw allow from &lt;remote-ip-address&gt; to any port 3306</pre><h3>Test Remote Access:</h3><p>To test if remote access is working:</p><ol><li>Attempt to connect to the MySQL server using the following command:</li></ol><pre>mysql -u dbuser -p -h &lt;public_ip OR url&gt; #OR<br><br>mysql -u dbuser -p -h &lt;public_ip OR url&gt; -P 3306 your_database</pre><ol><li>Replace &lt;public_ip or url&gt; with the public IP address of your server.</li><li>Enter the password for dbuser when prompted.</li><li>Once connected, verify access to the desired database:</li></ol><pre>SHOW DATABASES; <br>USE dbname;</pre><p>If the connection fails, check the following:</p><ul><li>Ensure the firewall allows traffic on port 3306.</li><li>Verify that the bind-address is correctly set.</li><li>Confirm the user privileges are configured for the remote IP address.</li></ul><h3>Step 11: Troubleshooting</h3><ul><li><strong>Access Denied Errors</strong>: If the user cannot connect remotely, check that the user has the appropriate privileges and that the MySQL service is bound to 0.0.0.0, and that firewall settings allow MySQL traffic.</li><li><strong>Check Logs</strong>: If you’re having trouble connecting, check MySQL logs for errors:</li></ul><pre>sudo tail -f /var/log/mysql/error.log</pre><p>You’ve successfully set up MySQL on a Cloud Server, created a database, created a user with specific privileges, and configured the server for local and remote access. Always ensure you’re following best practices for MySQL security, including using strong passwords, limiting user privileges, and regularly backing up your databases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62379fe58aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>