<?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 rashid pbi on Medium]]></title>
        <description><![CDATA[Stories by rashid pbi on Medium]]></description>
        <link>https://medium.com/@rashidpbi111?source=rss-b30d00318c09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_DyOZ4WpP0DNcmX7</url>
            <title>Stories by rashid pbi on Medium</title>
            <link>https://medium.com/@rashidpbi111?source=rss-b30d00318c09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:35:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rashidpbi111/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[TypeScript Fundamentals: A Practical Guide for JavaScript Developers]]></title>
            <link>https://medium.com/@rashidpbi111/typescript-fundamentals-a-practical-guide-for-javascript-developers-43faa341462f?source=rss-b30d00318c09------2</link>
            <guid isPermaLink="false">https://medium.com/p/43faa341462f</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[rashid pbi]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 18:35:11 GMT</pubDate>
            <atom:updated>2025-10-08T18:35:11.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Rrarn5Jyy2tqhuZM0aq_A.png" /></figure><p>TypeScript is a syntactic superset of JavaScript that adds static typing. In simple terms, it prevents us from shooting ourselves in the foot while writing code by catching errors during development that JavaScript wouldn’t warn us about. It’s like having a buddy who double-checks your work and stops you from doing something dumb — like passing a string to a function expecting a number or accessing a property that doesn’t exist.</p><p>Imagine you’re a freelance developer hired by a startup to fix their buggy e-commerce site. Frustrated with the constant bugs, you decide to introduce TypeScript to the project. Here’s what that journey looks like.</p><h3>Getting Started with TypeScript</h3><p>First, you install TypeScript by typing the following in the terminal:</p><pre>npm install typescript --save-dev</pre><p>Then you initialize a configuration file for TypeScript:</p><pre>npx tsc --init</pre><p>After that, you open your tsconfig.json file and see a bunch of lines. Among these, you&#39;ll find the <strong>compiler options</strong> field, which specifies options for the TypeScript compiler.</p><h3>Understanding Key Configuration Options</h3><p><strong>Target Field:</strong> TypeScript automatically selects the JavaScript version you want to use, but you can also choose to work with a more modern version such as ES2020 or ESNext. Think of it like choosing a car model — older models work everywhere, but newer ones come with more features.</p><p><strong>Module Field:</strong> By default, it’s set to CommonJS, which specifies the module system for JavaScript files. Modules are chunks of code that you can import and export between files. CommonJS is mostly used in Node.js and lets you use the require keyword to import and module.exports to export. Alternatively, you can work with modern module systems like ESNext or ES6 to use the import and export syntax.</p><p><strong>esModuleInterop:</strong> This acts as a bridge, smoothing out compatibility issues between the two module systems we discussed earlier.</p><p><strong>forceConsistentCasingInFileNames:</strong> As the name suggests, this ensures that imports match the case of file names, preventing errors on case-sensitive file systems.</p><p><strong>Strict Field:</strong> This enables strict type checking for your code, which is critical when using TypeScript.</p><p><strong>skipLibCheck:</strong> This skips type checking for library files, speeding up compilation by assuming that the library code is correct.</p><h3>Type Annotations: Your First Line of Defense</h3><p>Once you’re done with the config file, you tackle your first task: creating a user registration form where users must enter their name.</p><pre>let username = &quot;John Doe&quot;;</pre><p>This works well usually, but what if someone tries to input an invalid value, like mistakenly putting their phone number instead of their name?</p><p>TypeScript saves you from this mistake. You just need to specify which type of value you want the variable to accept:</p><pre>let username: string = &quot;John Doe&quot;;</pre><p>In our case, anything that isn’t a string will result in an error, which lets us handle it correctly.</p><h3>Working with Numbers</h3><p>Here’s another example with numbers. We have a variable for discount:</p><pre>let discount: number = 20;</pre><p>What if someone typed the word “twenty” instead of a numerical value? This could accidentally lead to a loss of revenue, and we definitely don’t want that.</p><h3>Boolean Types</h3><p>Let’s say we created a feature toggle for our beta users:</p><pre>let isBetaUser: boolean = true;</pre><p>To ensure type safety and prevent accidental misuse, we secure this variable using TypeScript.</p><h3>Arrays and Type Safety</h3><p>The marketing team wants to keep track of top-selling products. You create an array for the top sellers:</p><pre>let topSellers = [&quot;laptop&quot;, &quot;phone&quot;];</pre><p>This works well initially, but what if your team accidentally adds a non-product value like a number or a boolean?</p><pre>let topSellers: string[] = [&quot;laptop&quot;, &quot;phone&quot;];</pre><p>This restricts the array to accept only strings as its values.</p><h3>Union Types: Handling Multiple Types</h3><p>Your marketing team insists that they need to add numbers as some top products are represented as numbers. To handle this, you can adjust the type to also accept numbers using a <strong>union type</strong>:</p><pre>let topSellers: (string | number)[] = [&quot;laptop&quot;, &quot;phone&quot;, 123];</pre><p>Union operators can also be used with regular variables. For example, you’re building a user management system where the user can be identified by either a numeric user ID or a username:</p><pre>let userId: number | string;<br>userId = 12345;  // Valid<br>userId = &quot;john_doe&quot;;  // Also valid</pre><h3>TypeScript with Functions</h3><p>Imagine you’re building a loan calculation system. The function requires two number inputs and should return a number:</p><pre>function calculateLoan(amount: number, rate: number): number {<br>  return amount * rate;<br>}</pre><p>Without TypeScript, passing a string or object could break the function. By adding type annotations, we ensure that both the amount and rate only accept numbers, and the return statement only returns a number. Now, even if we accidentally change the return value to a string, TypeScript will give us an error.</p><h3>Interfaces: Structuring Objects</h3><p>Imagine you’re building an HR system to track employees. You want to ensure that the data about each employee is structured correctly.</p><p>An interface in TypeScript acts as a template for objects:</p><pre>interface Employee {<br>  id: number;<br>  name: string;<br>  position: string;<br>}</pre><pre>const employee: Employee = {<br>  id: 1,<br>  name: &quot;John Doe&quot;,<br>  position: &quot;Developer&quot;<br>};</pre><p>By defining the Employee interface, TypeScript makes sure that every employee object must follow this structure, preventing missing or incorrect fields.</p><h3>Optional Properties</h3><p>Sometimes employees don’t have a position yet because they might still be in a pending process. We can make interfaces flexible by providing optional properties:</p><pre>interface Employee {<br>  id: number;<br>  name: string;<br>  position?: string;  // Optional property<br>}</pre><p>You simply add a question mark to the field. This way, even if we create a new object without a position field, it will still be valid.</p><h3>Type Aliases: Custom Type Names</h3><p>A type alias is a way to give a type a new name. It allows you to define a custom type that can be used like any other type in your code.</p><p>Normally you would define a primitive type like this:</p><pre>let username: string = &quot;John&quot;;</pre><p>You can create a type alias to make the type more descriptive:</p><pre>type Username = string;<br>let username: Username = &quot;John&quot;;</pre><p>If you want to go further, you can define a more restrictive alias using literal types:</p><pre>type Username = &quot;John&quot; | &quot;Jane&quot; | &quot;Alex&quot;;<br>let username: Username = &quot;John&quot;;  // Valid<br>let username: Username = &quot;Bob&quot;;   // Error!</pre><h3>Real-World Example: User Roles</h3><p>User roles often determine what actions a user can perform in an application:</p><pre>type Role = &quot;admin&quot; | &quot;moderator&quot; | &quot;user&quot;;<br>let userRole: Role = &quot;admin&quot;;  // Valid<br>let userRole: Role = &quot;guest&quot;;  // Error!</pre><p>If you try to assign an invalid role, TypeScript will raise an error, ensuring that only valid roles are used.</p><h3>Enums: Named Constants</h3><p>Enums in TypeScript are a way to define named constant values. They make your code more readable and maintainable.</p><p>Imagine you’re building a subscription system:</p><pre>enum SubscriptionTier {<br>  Free,<br>  Basic,<br>  Premium<br>}</pre><pre>let userTier: SubscriptionTier = SubscriptionTier.Premium;</pre><p>Even if we accidentally try to assign something other than a valid enum value, TypeScript will give us an error.</p><h3>Enums with Numbers</h3><p>You can also use numbers for enums:</p><pre>enum HttpStatus {<br>  OK = 200,<br>  NotFound = 404,<br>  InternalServerError = 500<br>}</pre><pre>function handleResponse(status: HttpStatus) {<br>  switch(status) {<br>    case HttpStatus.OK:<br>      console.log(&quot;Success!&quot;);<br>      break;<br>    case HttpStatus.NotFound:<br>      console.log(&quot;Not found!&quot;);<br>      break;<br>  }<br>}</pre><p>This makes it much more secure and easier to handle functions with switches.</p><h3>Generics: Reusable Components</h3><p>A generic is a way to create a reusable component that can work for multiple data types. It’s simply a placeholder for any data type.</p><p>We have a function called identity where we don&#39;t know upfront what type of data will be passed:</p><pre>function identity&lt;T&gt;(arg: T): T {<br>  return arg;<br>}</pre><pre>let numberValue = identity&lt;number&gt;(42);    // Returns number<br>let stringValue = identity&lt;string&gt;(&quot;hello&quot;); // Returns string</pre><p>The generic placeholder T represents any data type. The argument type and the return type both use T, ensuring they are consistent. If we pass a number, TypeScript infers that both the argument and return value are of type number. Similarly with strings.</p><p>The function ensures that the type of the argument matches the type of the return value, which prevents issues that could occur in JavaScript where types are not enforced.</p><h3>Final Thoughts</h3><p>These are just the basics of TypeScript. The real power comes when you start using these features together in real-world applications. TypeScript might seem like extra work at first, but once you experience catching bugs before they reach production, you’ll wonder how you ever lived without it.</p><p>The key is to start small — add TypeScript to one file, then gradually expand. Before you know it, you’ll be writing safer, more maintainable code that your future self will thank you for.</p><p><em>Ready to dive deeper into TypeScript? Start by converting one of your existing JavaScript projects to TypeScript and see the difference it makes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43faa341462f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manual Installation of Frappe & ERPNext on Ubuntu: A Complete Guide]]></title>
            <link>https://medium.com/@rashidpbi111/manual-installation-of-frappe-erpnext-on-ubuntu-a-complete-guide-0223565730c9?source=rss-b30d00318c09------2</link>
            <guid isPermaLink="false">https://medium.com/p/0223565730c9</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[business-automation]]></category>
            <category><![CDATA[frappe-framework]]></category>
            <category><![CDATA[open-source-erp]]></category>
            <category><![CDATA[erpnext]]></category>
            <dc:creator><![CDATA[rashid pbi]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 13:20:24 GMT</pubDate>
            <atom:updated>2025-10-01T13:21:15.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTiFIkLmVM0PTtjmJDP6gw.jpeg" /></figure><p>Setting up ERPNext locally can seem daunting at first, but with a step-by-step approach, it becomes straightforward. In this guide, we’ll manually install Frappe and ERPNext on Ubuntu 22.04+ without using Docker.</p><h3>Prerequisites</h3><p>Update Ubuntu and install required packages:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install python3-dev python3-setuptools python3-pip python3-venv git mariadb-server mariadb-client redis-server curl nodejs npm yarn build-essential libffi-dev libssl-dev wkhtmltopdf -y</pre><p><strong>Note:</strong> Some packages like wkhtmltopdf may need manual download and installation (covered below).</p><h3>Step 1: Secure MariaDB</h3><p>Run the MariaDB shell:</p><pre>sudo mariadb</pre><p>Inside the MariaDB shell, set a root password:</p><pre>ALTER USER &#39;root&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;YourStrongPassword&#39;;<br>FLUSH PRIVILEGES;<br>EXIT;</pre><p>Create a Frappe database user:</p><pre>sudo mariadb</pre><pre>CREATE USER &#39;frappe&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;frappe123&#39;;<br>GRANT ALL PRIVILEGES ON *.* TO &#39;frappe&#39;@&#39;localhost&#39; WITH GRANT OPTION;<br>FLUSH PRIVILEGES;<br>EXIT;</pre><h3>Step 2: Install wkhtmltopdf</h3><p>Download the .deb package for your Ubuntu version from:</p><pre>https://wkhtmltopdf.org/downloads.html</pre><p>Install it:</p><pre>sudo dpkg -i ~/Downloads/wkhtmltox_0.12.6.1-2.jammy_amd64.deb<br>sudo apt -f install  # fix missing dependencies</pre><h3>Step 3: Setup Python Virtual Environment</h3><pre>python3 -m venv ~/frappe-env<br>source ~/frappe-env/bin/activate</pre><p>This ensures all Python packages are installed isolated from system Python, avoiding conflicts.</p><h3>Step 4: Install Bench CLI</h3><p>Bench is a command-line tool to manage Frappe sites.</p><pre>pip install frappe-bench</pre><p>Confirm installation:</p><pre>bench --version</pre><h3>⚠️ Important: Virtual Environment Activation Required</h3><p>The virtual environment must be activated every time you open a new terminal session to work with bench commands.</p><pre># REQUIRED for every new terminal session:<br>source ~/frappe-env/bin/activate</pre><p>You’ll know it’s activated when you see (frappe-env) at the beginning of your terminal prompt (like below) :</p><pre>(frappe-env) user@ubuntu:~$</pre><h3>Step 5: Initialize a Bench</h3><p>Create a working directory for your bench:</p><pre>cd ~<br>bench init &lt;directory name&gt;</pre><p>This will set up the Frappe environment with Redis, Node.js, and necessary Python dependencies.</p><h3>Step 6: Create a New Site</h3><pre>bench new-site erpnext.localhost --force</pre><p>You’ll be prompted to:</p><ul><li>Enter the MariaDB user credentials (the frappe user created earlier)</li><li>Set the Administrator password — this will be your login password for ERPNext</li></ul><h3>Step 7: Get ERPNext App</h3><pre>bench get-app https://github.com/frappe/erpnext</pre><p>This clones ERPNext into the apps folder and installs its Python dependencies. Build frontend assets with:</p><pre>bench build --app erpnext</pre><h3>Step 8: Install ERPNext on Your Site</h3><pre>bench --site erpnext.localhost install-app erpnext</pre><p>This links ERPNext to your site database and finalizes installation.</p><h3>Step 9: Start the Development Server</h3><pre>bench start</pre><p>Open your browser at:</p><pre>http://erpnext.localhost:8000/app</pre><p>Log in using the <strong>Administrator</strong> account and password set earlier.</p><h3>Important Notes &amp; Tips</h3><p><strong>Scheduler Disabled:</strong> Local development sites have the scheduler disabled by default; background jobs won’t run until enabled.</p><p><strong>Virtual Environment:</strong> Always activate your frappe-env before running bench commands.</p><p><strong>Dependencies:</strong> Node.js packages are installed via yarn; Python packages inside the virtual environment.</p><p><strong>Recreating Sites:</strong> If a site already exists, use --force with bench new-site to recreate it.</p><p><strong>Memory Overcommit Warning in Redis:</strong> Can be fixed for production with sudo sysctl vm.overcommit_memory=1, but safe to ignore in development.</p><h3>Your Local ERPNext is Ready</h3><p>You now have a fully functional local ERPNext environment, ready for development, testing, or learning.</p><p>This manual installation approach gives you complete control over your setup and helps you understand how Frappe and ERPNext work under the hood. While Docker installations are faster, knowing how to set up the environment manually is invaluable for troubleshooting and customization.</p><p><em>Have questions about the installation process? Run into any issues? Feel free to share your experience in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0223565730c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Complexity of Web Authentication: Why Every Developer Should Build Their Own (At Least…]]></title>
            <link>https://medium.com/@rashidpbi111/the-hidden-complexity-of-web-authentication-why-every-developer-should-build-their-own-at-least-ac300bbde89c?source=rss-b30d00318c09------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac300bbde89c</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[rashid pbi]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 01:54:43 GMT</pubDate>
            <atom:updated>2025-08-28T01:54:43.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Hidden Complexity of Web Authentication: Why Every Developer Should Build Their Own (At Least Once)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHk5zw1Dyz7Q0-UpvAc2iQ.jpeg" /></figure><p>Picture this: You’re building your next web application, and authentication is on your todo list. Your first instinct? Reach for Clerk, Auth0, or NextAuth.js. They’re battle-tested, secure, and save you weeks of development time. But here’s the thing — by always taking the easy route, you might be missing out on understanding one of the most critical aspects of web security.</p><p>After implementing my own OAuth 2.0 authentication system from scratch, I discovered that what seems like straightforward user management is actually a minefield of edge cases, security considerations, and subtle gotchas that can break your application in production.</p><h3>The Authentication Trinity: More Than Just Login Forms</h3><p>Most developers think of authentication as simply verifying usernames and passwords. But in reality, modern web authentication involves three interconnected concepts that work together:</p><p><strong>Authentication</strong> is about identity verification — proving who the user claims to be. This happens when someone enters their credentials or connects through OAuth providers like Google or GitHub.</p><p><strong>Authorization</strong> determines what that authenticated user can actually do within your application. Just because someone can log in doesn’t mean they should access admin panels or sensitive data.</p><p><strong>Redirection</strong> ties everything together by controlling the user’s journey through your application. It ensures logged-in users don’t see login pages and unauthenticated users can’t access protected content.</p><p>The magic happens in how these three work together. When a user logs in through Google OAuth, they’re redirected to Google’s servers for authentication, then back to your app with an authorization code, which you exchange for tokens that determine what they can access. Miss any step in this dance, and your security falls apart.</p><h3>The Token Juggling Act: Where Things Get Complicated</h3><p>OAuth 2.0 introduces a layer of complexity that catches many developers off guard. Unlike simple session-based authentication, OAuth involves managing two types of tokens with different lifespans and purposes.</p><p><strong>Access tokens</strong> are your golden tickets — they prove the user is authenticated and authorized to access resources. But they’re intentionally short-lived, typically expiring after just one hour. This creates a user experience problem: nobody wants to log in every hour.</p><p><strong>Refresh tokens</strong> solve this by lasting much longer (usually about a week) and can generate new access tokens behind the scenes. But here’s where it gets tricky — these refresh tokens are only provided during the initial authorization flow. If something goes wrong and you lose them, the user has to start over.</p><p>This is where understanding beats blindly using libraries. When you know why tokens work this way, you can design your application flow to preserve them properly.</p><h3>Battle-Tested Lessons from the Trenches</h3><p>When I built my own authentication system, I encountered scenarios that no tutorial prepared me for. These real-world edge cases taught me more about web security than any documentation could.</p><h3>The Refresh Token Trap</h3><p>Google’s OAuth 2.0 has a gotcha that bit me hard: refresh tokens are only provided during the first authorization. If a logged-in user accidentally visits your login page and goes through OAuth again, Google won’t provide a new refresh token. Your application loses the ability to refresh access tokens, effectively logging the user out after an hour.</p><p>The solution? Implement smart redirection logic that prevents authenticated users from accessing the login flow. This isn’t just about user experience — it’s about maintaining authentication state.</p><h3>Storage Security: The XSS Vulnerability</h3><p>Where you store tokens matters more than you might think. Local storage seems convenient, but it’s vulnerable to XSS attacks. Any malicious script can read and steal tokens, compromising user accounts.</p><p>Server-side storage or secure HTTP-only cookies are the way to go. The tokens never touch client-side JavaScript, making them much harder for attackers to steal.</p><h3>The Graceful Degradation Challenge</h3><p>What happens when refresh tokens expire? Many developers handle this poorly, showing confusing error messages or breaking the user experience. The elegant solution is to detect token expiry in your API layer and automatically redirect users back to login with a helpful message.</p><p>This requires understanding the token lifecycle well enough to implement proper error handling throughout your application.</p><h3>Why Libraries Can’t Teach You Everything</h3><p>Don’t get me wrong — authentication libraries are fantastic. They handle the heavy lifting of security best practices, token management, and provider integrations. But they also abstract away the underlying mechanics that you need to understand when things go wrong.</p><p>When your production application starts throwing authentication errors at 2 AM, you need to understand whether it’s a token expiry issue, a storage problem, or a redirection loop. Libraries can’t debug themselves — you need to understand what’s happening under the hood.</p><p>Building your own authentication system once gives you this x-ray vision into how modern web authentication actually works. You’ll understand why certain design decisions were made, what trade-offs exist between security and user experience, and how to extend or customize library behavior when needed.</p><h3>The Learning Investment That Pays Dividends</h3><p>I’m not suggesting you reinvent the wheel for every project. Use trusted libraries for production applications. But invest time in building your own authentication flow at least once, perhaps as a side project or learning exercise.</p><p>You’ll gain intuition about:</p><ul><li>How OAuth flows actually work beyond the surface level</li><li>Why certain security practices exist and when to apply them</li><li>How to debug authentication issues in production</li><li>When and how to customize library behavior safely</li></ul><p>This knowledge transforms you from a developer who implements authentication to one who understands it. And in a world where security breaches make headlines daily, that understanding is invaluable.</p><p>The next time you reach for an authentication library, you’ll do so with confidence, knowing not just how to use it, but why it works the way it does. That’s the difference between writing code and engineering secure applications.</p><p><em>Ready to dive deeper into web authentication? Start with implementing a simple OAuth 2.0 flow with Google’s APIs. The documentation is excellent, and the lessons you’ll learn will serve you throughout your career.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac300bbde89c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced React Patterns for Cleaner, Scalable Components]]></title>
            <link>https://medium.com/@rashidpbi111/advanced-react-patterns-for-cleaner-scalable-components-a64b06c66cee?source=rss-b30d00318c09------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64b06c66cee</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[rashid pbi]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 21:34:41 GMT</pubDate>
            <atom:updated>2025-08-23T21:34:41.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pg3SFsVDs4WLVH9B5uTqWQ.png" /></figure><p><em>How I learned to stop worrying and love component architecture</em></p><p>I’ve been refactoring a lot of React code lately, and honestly? Some of it was a mess. Components doing way too much, logic scattered everywhere, and that classic “it works but I’m scared to touch it” feeling.</p><p>Here are the patterns that actually helped me write components I can come back to six months later without wanting to rewrite everything.</p><h3>The Single Responsibility Revolution</h3><p>This sounds obvious until you realize your UserProfile component is fetching data, handling forms, managing modals, AND rendering the UI. Yeah, been there.</p><p><strong>Better approach:</strong></p><pre>Homepage<br>├─ PostFeed (renders list)<br>│  ├─ PostCard (single post UI)<br>│  ├─ PostCard<br>│  └─ PostCard<br>└─ PostFilters (search/filter logic)</pre><p>Each component has <strong>one clear job</strong>:</p><ul><li>Homepage → coordinates everything</li><li>PostFeed → takes posts, renders them</li><li>PostCard → displays one post, that&#39;s it</li></ul><p>The magic happens when PostCard becomes so simple you can drop it anywhere. Need posts in a sidebar? Done. Want them in a modal? Easy.</p><h3>The Three-Layer Architecture That Changed Everything</h3><p>I organize every feature into three types of components, and it’s saved me so much headache:</p><pre>LoginPage (Page Component)<br>└─ LoginForm (Feature Component)<br>   ├─ TextInput (UI Component)<br>   └─ Button (UI Component)</pre><p><strong>UI Components</strong> → Just visual stuff. No state, no API calls, pure presentation.</p><p><strong>Feature Components</strong> → Handle one specific thing. LoginForm knows about validation, form submission, error handling.</p><p><strong>Page Components</strong> → The conductor. Orchestrates features, handles routing, manages page-level state.</p><p>This means when the designer wants to change button styles, I touch UI components. When business logic changes, I touch features. When we add analytics, I touch pages. Clean separation = fewer bugs.</p><h3>Compound Components: The Underrated Pattern</h3><p>Ever used something like this?</p><pre>&lt;Select&gt;<br>  &lt;Select.Option value=&quot;react&quot;&gt;React&lt;/Select.Option&gt;<br>  &lt;Select.Option value=&quot;vue&quot;&gt;Vue&lt;/Select.Option&gt;<br>  &lt;Select.Option value=&quot;svelte&quot;&gt;Svelte&lt;/Select.Option&gt;<br>&lt;/Select&gt;</pre><p>That’s a compound component. The Select and Select.Option share state behind the scenes, but the API feels natural.</p><p><strong>Quick implementation:</strong></p><pre>const SelectContext = createContext();</pre><pre>function Select({ children }) {<br>  const [value, setValue] = useState(null);<br>  return (<br>    &lt;SelectContext.Provider value={{ value, setValue }}&gt;<br>      &lt;div className=&quot;select&quot;&gt;{children}&lt;/div&gt;<br>    &lt;/SelectContext.Provider&gt;<br>  );<br>}</pre><pre>function Option({ value, children }) {<br>  const { setValue } = useContext(SelectContext);<br>  return (<br>    &lt;div onClick={() =&gt; setValue(value)}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>Select.Option = Option; // This is the magic line</pre><p>Perfect for complex components where you need shared state but want clean usage.</p><h3>Extract Everything Into Hooks (Even If You Think You Don’t Need To)</h3><p>This one changed how I write components. Even if a hook is only used once, I still extract the logic.</p><p><strong>Instead of this:</strong></p><pre>function ProfilePage() {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  <br>  useEffect(() =&gt; {<br>    fetchUser().then(setUser).finally(() =&gt; setLoading(false));<br>  }, []);</pre><pre>  // ... more logic</pre><pre>  return &lt;div&gt;{/* UI stuff */}&lt;/div&gt;;<br>}</pre><p><strong>I do this:</strong></p><pre>function ProfilePage() {<br>  const { user, loading, updateProfile } = useProfilePage();<br>  return &lt;div&gt;{/* Just UI stuff */}&lt;/div&gt;;<br>}</pre><pre>function useProfilePage() {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  <br>  useEffect(() =&gt; {<br>    fetchUser().then(setUser).finally(() =&gt; setLoading(false));<br>  }, []);</pre><pre>  return { user, loading, updateProfile };<br>}</pre><p>Now my component is just JSX and the hook handles all the messy logic. Testing becomes easier, the component is more readable, and if I need similar logic elsewhere, I can reuse the hook.</p><h3>Why This Actually Matters</h3><p>These aren’t just “clean code” exercises. They solve real problems:</p><p><strong>Debugging is faster</strong> → When something breaks, I know exactly where to look</p><p><strong>Changes are safer</strong> → Want to modify how posts are fetched? Only one place to change it</p><p><strong>New features are easier</strong> → Need a new page with similar functionality? Compose existing pieces</p><p><strong>Testing is simpler</strong> → Test hooks separately from UI, test UI separately from logic</p><h3>The Bottom Line</h3><p>I used to think these patterns were overkill for smaller projects. Turns out, starting with good architecture from day one prevents the “let’s just rewrite this” conversation later.</p><p>Your future self will thank you when you can actually understand the code you wrote last month.</p><p><em>What patterns have saved you the most headaches in your React projects?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64b06c66cee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>