<?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 Hassnain on Medium]]></title>
        <description><![CDATA[Stories by Hassnain on Medium]]></description>
        <link>https://medium.com/@KhanHassnain?source=rss-79158af197f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zKtU1NIoccrdaNKeFMLVyQ.jpeg</url>
            <title>Stories by Hassnain on Medium</title>
            <link>https://medium.com/@KhanHassnain?source=rss-79158af197f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:37:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@KhanHassnain/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[Understanding Layered Architecture in ASP.NET Core: Building My FinFlow API Step by Step]]></title>
            <link>https://medium.com/@KhanHassnain/understanding-layered-architecture-in-asp-net-core-with-finflow-a7ad11adeca6?source=rss-79158af197f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7ad11adeca6</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Hassnain]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 15:32:19 GMT</pubDate>
            <atom:updated>2026-10-17T15:36:58.323Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A practical guide to separating responsibilities, organizing backend code, and understanding how an API request reaches the database.</strong></p><p>When I started exploring backend development with ASP.NET Core, one of the first things I wanted to understand was how real-world applications organize their code.</p><p>Creating an API endpoint is relatively straightforward. You can receive an HTTP request, execute some logic, interact with a database, and return a response from a single file.</p><p>But what happens when an application grows?</p><p>What if it has users, accounts, transactions, authentication, business rules, and multiple database operations? What if the same business logic needs to be reused by different endpoints? And what happens when we need to change the database implementation?</p><p>Putting everything into one place can quickly make a codebase difficult to maintain.</p><p>To explore these problems practically, I started building <strong>FinFlow</strong>, a finance-focused backend project using ASP.NET Core, C#, Entity Framework Core, and SQL Server.</p><p>In this article, I’ll explain how I organized FinFlow using a layered architecture, what each project is responsible for, how the layers communicate, and how a transaction request can travel from an API endpoint to the database.</p><p>The goal is not just to understand the folder structure, but to understand the reasoning behind it.</p><h3>1. What Is Layered Architecture?</h3><p>Layered architecture is a software design approach in which an application is divided into separate layers, each responsible for a particular part of the system.</p><p>Instead of putting HTTP handling, business logic, and database operations into one place, we separate these responsibilities.</p><p>For example, consider an API that creates a financial transaction.</p><p>The application needs to:</p><ol><li>Receive the HTTP request.</li><li>Validate the incoming data.</li><li>Execute the relevant application logic.</li><li>Save the transaction to the database.</li><li>Return an appropriate HTTP response.</li></ol><p>These responsibilities are related, but they are not the same.</p><p>The API layer should not need to know the details of SQL queries. The database implementation should not need to know about HTTP status codes. And the business logic should not be tightly coupled to a particular endpoint.</p><p>That is the problem layered architecture helps us address.</p><h3>2. The Architecture I Used in FinFlow</h3><p>My FinFlow solution is organized into four projects:</p><ul><li>FinFlow.Api</li><li>FinFlow.Application</li><li>FinFlow.Domain</li><li>FinFlow.Infrastructure</li></ul><p>Each project has a different responsibility.</p><h3>FinFlow architecture at a glance</h3><pre>HTTP Request<br>                       |<br>                       v<br>                +--------------+<br>                |  FinFlow.Api |<br>                +--------------+<br>                       |<br>                       v<br>             +--------------------+<br>             | FinFlow.Application|<br>             +--------------------+<br>                       |<br>                       v<br>             +----------------------+<br>             | FinFlow.Infrastructure|<br>             +----------------------+<br>                       |<br>                       v<br>                +--------------+<br>                |  SQL Server  |<br>                +--------------+</pre><p>FinFlow.Domain contains the core business entities and domain concepts used by the application. It supports the other layers rather than acting as another HTTP or database-processing step.</p><p>The diagram shows the simplified runtime flow of a typical transaction request. The exact dependency direction is important too, and we will look at it below.</p><h3>3. Understanding Each Project</h3><h3>A. FinFlow.Api — The Entry Point</h3><p>The API project is the entry point of the application.</p><p>It handles HTTP communication between a client and the backend. That client could be a Flutter application, a React Native application, a web application, or Postman.</p><p>Responsibilities of this layer include:</p><ul><li>Exposing HTTP endpoints.</li><li>Receiving request data.</li><li>Applying request-level validation.</li><li>Calling the appropriate application service.</li><li>Returning HTTP responses and status codes.</li></ul><p>For example, a transaction endpoint might accept a request like this:</p><pre>POST /api/transactions<br>Content-Type: application/json</pre><p>With a JSON body:</p><pre>{<br>  &quot;amount&quot;: 2500,<br>  &quot;description&quot;: &quot;Monthly expense&quot;<br>}</pre><p>The API receives the request, but it should not contain all the logic required to save a transaction.</p><p>A simplified controller example looks like this:</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class TransactionsController : ControllerBase<br>{<br>    private readonly ITransactionService _transactionService;</pre><pre>    public TransactionsController(<br>        ITransactionService transactionService)<br>    {<br>        _transactionService = transactionService;<br>    }</pre><pre>    // HTTP endpoints call the application service.<br>}</pre><p>This example illustrates the controller pattern. If the current FinFlow implementation uses Minimal APIs instead of controllers, the same separation can be achieved through endpoint handlers.</p><p>Notice the constructor parameter:</p><pre>ITransactionService transactionService</pre><p>The controller depends on an interface rather than directly creating a TransactionService instance.</p><p>This is an example of dependency injection.</p><p>ASP.NET Core can provide the appropriate implementation at runtime through its dependency injection container.</p><p><strong>Why is this useful?</strong></p><p>The API layer does not need to know how the transaction is created internally. It only needs to know which application service to call.</p><p>This keeps HTTP concerns separate from the rest of the application.</p><h3>B. FinFlow.Application — Coordinating the Work</h3><p>The Application project coordinates the operations required to complete a use case.</p><p>In FinFlow, this includes the transaction service and the abstractions it uses to access data.</p><p>For example:</p><pre>FinFlow.Application/<br>    Services/<br>        TransactionService.cs<br>    Interfaces/<br>        ITransactionService.cs<br>        ITransactionRepository.cs<br>    DTOs/<br>        ...</pre><p>This is an illustrative organization; the actual folder names depend on the current repository structure.</p><p>Let’s understand the role of each component.</p><p><strong>ITransactionService</strong></p><p>This interface defines the operations the API can request from the transaction application service.</p><p>A simplified example:</p><pre>public interface ITransactionService<br>{<br>    Task&lt;IEnumerable&lt;Transaction&gt;&gt; GetAllAsync();<br>}</pre><p>The interface defines a contract. It does not specify the full implementation.</p><p><strong>TransactionService</strong></p><p>The service implements the application logic.</p><p>For example:</p><pre>public class TransactionService : ITransactionService<br>{<br>    private readonly ITransactionRepository _repository;</pre><pre>    public TransactionService(<br>        ITransactionRepository repository)<br>    {<br>        _repository = repository;<br>    }</pre><pre>    public async Task&lt;IEnumerable&lt;Transaction&gt;&gt; GetAllAsync()<br>    {<br>        return await _repository.GetAllAsync();<br>    }<br>}</pre><p>This is a simplified example to demonstrate the dependency relationship, not a claim that the current FinFlow method has exactly this signature.</p><p>The service receives ITransactionRepository through constructor injection.</p><p>Instead of querying SQL Server directly, it delegates the data operation to the repository abstraction.</p><p>In a larger application, this service could also coordinate multiple operations, enforce use-case rules, or map between DTOs and domain entities.</p><p>An important distinction: not every application needs a service that simply forwards calls to a repository. As business logic grows, the service should provide meaningful application-level responsibilities rather than becoming an unnecessary extra layer.</p><h3>C. FinFlow.Domain — The Core Business Model</h3><p>The Domain project represents the core concepts of the application.</p><p>In a finance application, these concepts might include:</p><ul><li>Transactions</li><li>Accounts</li><li>Wallets</li><li>Financial amounts</li><li>Business rules associated with these concepts</li></ul><p>A simplified transaction entity might look like this:</p><pre>public class Transaction<br>{<br>    public int Id { get; set; }</pre><pre>    public decimal Amount { get; set; }</pre><pre>    public string Description { get; set; } = string.Empty;<br>}</pre><p>This is an illustrative entity, not necessarily the complete entity in FinFlow.</p><p>The purpose of the example is to show that a transaction has application data independent of HTTP requests or database connection settings.</p><p>For example, decimal is generally appropriate for monetary amounts because it supports decimal arithmetic more suitably than binary floating-point types.</p><p>A production finance system would need additional considerations, including currency, precision, ownership, transaction status, timestamps, and appropriate business rules.</p><p><strong>Why keep Domain separate?</strong></p><p>Business concepts should not depend unnecessarily on controllers, HTTP responses, database connections, or infrastructure-specific implementations.</p><p>A domain model can then be reused by different application operations without tying the business model to one delivery mechanism.</p><h3>D. FinFlow.Infrastructure — Implementing Data Access</h3><p>Infrastructure contains implementation details for external systems, including database access.</p><p>In FinFlow, the important components include:</p><ul><li>ITransactionRepository as the data-access contract.</li><li>TransactionRepository as the concrete repository implementation.</li><li>FinFlowDbContext as the Entity Framework Core database context.</li><li>SQL Server as the database provider.</li></ul><p>The Application layer can define what it needs from a repository, while Infrastructure provides the actual implementation.</p><p>For example, a repository contract might look like this:</p><pre>public interface ITransactionRepository<br>{<br>    Task&lt;IEnumerable&lt;Transaction&gt;&gt; GetAllAsync();<br>}</pre><p>Infrastructure can implement that contract using Entity Framework Core:</p><pre>public class TransactionRepository : ITransactionRepository<br>{<br>    private readonly FinFlowDbContext _context;</pre><pre>    public TransactionRepository(<br>        FinFlowDbContext context)<br>    {<br>        _context = context;<br>    }</pre><pre>    public async Task&lt;IEnumerable&lt;Transaction&gt;&gt; GetAllAsync()<br>    {<br>        return await _context.Transactions<br>            .AsNoTracking()<br>            .ToListAsync();<br>    }<br>}</pre><p>Again, this is a representative example. It assumes that FinFlowDbContext exposes a Transactions DbSet and that the repository contract uses the same return type.</p><p>Let’s break it down.</p><p>FinFlowDbContext represents the session through which Entity Framework Core interacts with the database.</p><p>_context.Transactions refers to the entity set mapped to the transaction table.</p><p>AsNoTracking() tells EF Core not to track the returned entities for changes. This is useful for read-only queries when change tracking is unnecessary.</p><p>ToListAsync() executes the query asynchronously and materializes the results into a list.</p><p>The repository hides these database-specific details from the service.</p><p>That means the service works with the repository abstraction instead of needing to know how Entity Framework Core retrieves the data.</p><h3>4. What Is the Difference Between an Interface and Its Implementation?</h3><p>This was an important concept to understand while learning how the layers communicate.</p><p>Consider these two components:</p><pre>ITransactionRepository</pre><p>and</p><pre>TransactionRepository</pre><p>The interface describes what operations are available.</p><p>The implementation defines how those operations are performed.</p><p>For example:</p><pre>public interface ITransactionRepository<br>{<br>    Task&lt;IEnumerable&lt;Transaction&gt;&gt; GetAllAsync();<br>}</pre><p>The implementation may use Entity Framework Core and SQL Server to retrieve transactions.</p><pre>public class TransactionRepository : ITransactionRepository<br>{<br>    // Database access implementation.<br>}</pre><p>The Application layer can depend on the interface without knowing the database implementation details.</p><p>This is useful because implementations can evolve independently, provided they continue to satisfy the same contract.</p><p>It also makes it easier to replace an implementation during testing or when application requirements change.</p><p>However, an interface alone does not guarantee loose coupling. The dependency structure and the responsibilities of each layer matter just as much.</p><h3>5. Dependency Injection: How Do the Pieces Connect?</h3><p>Creating interfaces and implementation classes is only part of the solution.</p><p>ASP.NET Core also needs to know which implementation should be used when a class requests an interface.</p><p>This is where dependency injection and service registration come in.</p><p>A simplified registration example looks like this:</p><pre>builder.Services.AddScoped&lt;<br>    ITransactionService,<br>    TransactionService&gt;();</pre><pre>builder.Services.AddScoped&lt;<br>    ITransactionRepository,<br>    TransactionRepository&gt;();</pre><p>These registrations tell the dependency injection container which concrete type to provide for each interface.</p><p>When an API handler requests ITransactionService, ASP.NET Core can construct TransactionService.</p><p>When TransactionService requests ITransactionRepository, the container can provide TransactionRepository.</p><p>When the repository requests FinFlowDbContext, that context must also be registered, typically through Entity Framework Core&#39;s SQL Server configuration.</p><p>For example, the database configuration generally follows this pattern:</p><pre>builder.Services.AddDbContext&lt;FinFlowDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p>The exact configuration should match the actual FinFlow Program.cs and configuration files.</p><p>AddScoped registers a service with a lifetime scoped to a request in a typical ASP.NET Core web application. This is commonly appropriate for application services and repositories that use a scoped EF Core context.</p><p>The important idea is that the controller or service does not need to instantiate its dependencies manually.</p><p>ASP.NET Core manages the object graph for us.</p><h3>6. Following a Request from the API to SQL Server</h3><p>Let’s connect everything using a simple example.</p><p>Suppose a client requests all transactions.</p><pre>GET /api/transactions</pre><p>The request follows this logical path:</p><p><strong>Step 1: API</strong></p><p>The API receives the HTTP request and calls the transaction service.</p><p><strong>Step 2: Application</strong></p><p>TransactionService handles the application operation and calls the repository through ITransactionRepository.</p><p><strong>Step 3: Infrastructure</strong></p><p>TransactionRepository uses FinFlowDbContext to query the database through Entity Framework Core.</p><p><strong>Step 4: SQL Server</strong></p><p>SQL Server processes the generated query and returns the matching data.</p><p><strong>Step 5: Response</strong></p><p>The results travel back through the repository and service to the API, which returns an HTTP response.</p><p>The simplified flow is:</p><pre>Client / Postman<br>       |<br>       | GET /api/transactions<br>       v<br>    FinFlow.Api<br>       |<br>       v<br>TransactionService<br>       |<br>       v<br>ITransactionRepository<br>       |<br>       v<br>TransactionRepository<br>       |<br>       v<br> FinFlowDbContext<br>       |<br>       v<br>   SQL Server<br>       |<br>       v<br> Results returned to client</pre><p>This is the logical call flow. The Domain project supports the model and business concepts used by these operations rather than requiring a separate runtime call to Domain.</p><p>The same overall separation applies to create, update, and delete operations, although each operation has different validation and persistence requirements.</p><h3>7. How Does CRUD Fit into This Architecture?</h3><p>CRUD stands for Create, Read, Update, and Delete.</p><p>In FinFlow, I implemented and tested the four basic HTTP operations.</p><p>OperationHTTP methodTypical purposeCreatePOSTCreate a transactionReadGETRetrieve transactionsUpdatePUTUpdate an existing transactionDeleteDELETEDelete a transaction</p><p>For example:</p><pre>GET    /api/transactions<br>POST   /api/transactions<br>PUT    /api/transactions/1<br>DELETE /api/transactions/1</pre><p>These routes are illustrative. The actual routes depend on how the endpoints are defined in the project.</p><p>The important point is that CRUD does not have to be implemented entirely inside the API layer.</p><p>The API handles HTTP communication, the Application layer coordinates the operation, and Infrastructure handles database access.</p><p>This separation makes it easier to maintain the same architectural boundaries as new endpoints are added.</p><h3>8. DTO Validation: Why Is It Important?</h3><p>A backend API should not blindly trust incoming client data.</p><p>A mobile application can contain bugs, a request can be malformed, or someone can send a request manually through Postman.</p><p>For that reason, request validation is an important part of API development.</p><p>A Data Transfer Object, or DTO, represents the data accepted or returned by an API operation.</p><p>For example, a create-transaction request might use a DTO such as:</p><pre>public class CreateTransactionDto<br>{<br>    [Required]<br>    [Range(typeof(decimal), &quot;0.01&quot;, &quot;999999999&quot;)]<br>    public decimal Amount { get; set; }</pre><pre>    [Required]<br>    [StringLength(200)]<br>    public string Description { get; set; } = string.Empty;<br>}</pre><p>This example demonstrates validation attributes for a positive amount and a description with a maximum length. The limits are illustrative and should reflect actual business requirements.</p><p>The DTO allows the API to define the expected request shape without requiring the client to submit every property of the domain entity.</p><p>For example, a client should not necessarily be allowed to decide a transaction’s database ID or set internal fields directly.</p><p>With [ApiController], ASP.NET Core MVC can automatically return a validation error response when model validation fails. Minimal API applications may use different validation mechanisms depending on their configuration.</p><p>In my FinFlow learning process, I added validation and tested both valid and invalid requests through Postman.</p><p>That was useful because it showed the difference between an endpoint that merely accepts data and an endpoint that checks whether the request satisfies its input rules.</p><p>It is worth remembering that DTO validation does not replace business validation. Rules such as whether an account has sufficient funds or whether a user is authorized to update a transaction require additional application-level checks.</p><h3>9. Why Not Put Everything in One Controller?</h3><p>For a very small demonstration API, placing a small amount of logic in one file can be perfectly reasonable.</p><p>The problem appears when responsibilities start accumulating.</p><p>Imagine a controller that:</p><ul><li>Reads the HTTP request.</li><li>Validates every business rule.</li><li>Builds SQL queries.</li><li>Opens database connections.</li><li>Saves records.</li><li>Handles mapping.</li><li>Determines every error response.</li></ul><p>As the application grows, that controller becomes harder to understand and change.</p><p>Layered architecture gives each responsibility a more appropriate home.</p><p>Without clear separationWith layered separationHTTP and business logic are mixedHTTP handling is separated from application logicDatabase details leak into servicesData access is implemented behind a repository contractChanges can affect unrelated responsibilitiesChanges can often remain within the relevant layerDependencies are difficult to replaceInterfaces can help decouple implementationsTesting individual responsibilities is harderComponents can be tested at different levels</p><p>This does not mean layered architecture automatically makes every project clean. Poorly designed layers can still produce duplicated logic, unnecessary abstractions, or complicated dependency chains.</p><p>The goal is meaningful separation, not creating more files simply for the sake of it.</p><h3>10. How Is This Different from Clean Architecture?</h3><p>Layered architecture and Clean Architecture are related, but they are not exactly the same.</p><p>Layered architecture commonly separates an application into presentation, application or business logic, and data-access responsibilities.</p><p>Clean Architecture places particular emphasis on the direction of dependencies: inner business rules should not depend on outer infrastructure details.</p><p>FinFlow’s separate Api, Application, Domain, and Infrastructure projects help establish those boundaries.</p><p>A useful dependency principle is:</p><pre>API ───────────────&gt; Application<br>Infrastructure ────&gt; Application abstractions<br>Application ───────&gt; Domain<br>Infrastructure ────&gt; Domain</pre><p>The exact project references should be verified in the solution file.</p><p>For example, if ITransactionRepository is defined in Application and implemented in Infrastructure, Infrastructure references the abstraction&#39;s assembly. Application does not need to reference Infrastructure just to use the repository contract.</p><p>This approach is often associated with Dependency Inversion and Clean Architecture principles.</p><p>However, a project with separate layers is not automatically a complete Clean Architecture implementation. The details of dependency direction, business rules, and framework coupling determine how closely it follows that approach.</p><p>For FinFlow, the important learning outcome is understanding why these dependencies exist and how to keep them intentional.</p><h3>11. What I Learned from Building FinFlow</h3><p>Working through this project has helped me understand several backend concepts more practically.</p><p><strong>First, an API endpoint is only one part of a backend system.</strong> A reliable application also needs appropriate validation, application logic, persistence, and error handling.</p><p><strong>Second, interfaces define boundaries.</strong> An application service does not need to know how the repository performs its database operations.</p><p><strong>Third, Entity Framework Core simplifies database interaction, but it does not remove the need to understand SQL and database design.</strong> Developers still need to understand queries, relationships, constraints, indexes, and transactions.</p><p><strong>Fourth, validation is part of API reliability.</strong> Testing invalid requests is just as important as checking successful responses.</p><p><strong>Finally, architecture should help the application evolve.</strong> The point of separating projects is to make responsibilities easier to reason about, not to make a small project unnecessarily complicated.</p><p>FinFlow is still an evolving learning project, and there are additional areas to explore, including authentication, authorization, transaction consistency, automated testing, logging, and deployment.</p><h3>Conclusion</h3><p>Building FinFlow has been a practical way for me to move beyond simply creating endpoints and start understanding how backend applications are structured.</p><p>Layered architecture has helped me connect several concepts that can otherwise seem unrelated: dependency injection, interfaces, application services, repositories, Entity Framework Core, SQL Server, and API validation.</p><p>The most important takeaway is simple:</p><p><strong>Good backend development is not only about making an endpoint work. It is also about organizing the code so that the application remains understandable, maintainable, and ready to evolve.</strong></p><p>I’ll continue developing FinFlow and sharing what I learn as I explore more of ASP.NET Core and backend engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7ad11adeca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom hooks in React Native: Rules and usage]]></title>
            <link>https://medium.com/@KhanHassnain/custom-hooks-in-react-native-rules-and-usage-06793daf3f47?source=rss-79158af197f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/06793daf3f47</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Hassnain]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 15:51:06 GMT</pubDate>
            <atom:updated>2026-08-02T15:51:06.599Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been writing React Native for a while, you’ve probably noticed the same piece of logic showing up in screen after screen like fetching data, tracking keyboard visibility, checking network status, managing a form. Copy-pasting that logic (or worse, re-deriving it) is a sign you need a <strong>custom hook</strong>.</p><p>This blog breaks down what custom hooks are, the rules you must follow, and walks through a real, practical example you’ll actually use in production: a <strong>useNetworkStatus</strong> hook for handling offline states in a React Native app.</p><p><strong>Lets goo !!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*xo1rPSixuC0g-WbM8gzyEA.png" /></figure><p><strong>What Is a Custom Hook?</strong></p><p>A custom hook is just a JavaScript function whose name starts with <strong>use</strong> and that calls one or more of React&#39;s built-in hooks (<strong>useState</strong>, <strong>useEffect</strong>, <strong>useRef</strong>, etc.) inside it. That&#39;s it, there&#39;s no special API, no new syntax. React treats any function prefixed with <strong>use</strong> as a hook and applies the Rules of Hooks to it.</p><p>Custom hooks let you:</p><ul><li><strong>Extract and reuse stateful logic</strong> across components without changing your component tree (unlike render props or HOCs)</li><li><strong>Keep components thin</strong>, focused on rendering rather than logic</li><li><strong>Test logic in isolation</strong>, independent of UI</li></ul><p>In React Native specifically, custom hooks are the natural home for things like device APIs (NetInfo, AsyncStorage, permissions), animations (Reanimated), navigation state, and app lifecycle events (AppState).</p><p><strong>The Rules of Hooks (and Why They Exist)</strong></p><p>These rules apply to built-in hooks and custom hooks, since custom hooks are built from built-in ones.</p><h3>1. Only call hooks at the top level</h3><p>Never call hooks inside loops, conditions, or nested functions.</p><pre>const [user, setUser] = useState(null);<br>if (isLoggedIn) {<br>  // use user here<br>}</pre><p><strong>Why:</strong> React tracks hooks by the <em>order</em> they’re called in, not by name. Skipping a hook conditionally shifts every hook after it, corrupting React’s internal state.</p><h3>2. Only call hooks from React functions</h3><p>Call hooks only from React function components or from other custom hooks, never from regular JavaScript functions, class components, or event handlers.</p><pre>function MyComponent() {<br>  const [count, setCount] = useState(0);<br>  function handlePress() {<br>    setCount(c =&gt; c + 1);<br>  }<br>}</pre><h3>3. Name it use...</h3><p>This isn’t just a convention, it’s how the ESLint <strong>react-hooks </strong>plugin and React itself know to apply the hooks rules to your function. <strong>useAuth</strong>, <strong>useNetworkStatus</strong>, <strong>useFetchProduct, </strong>all correctly signal &quot;this follows the rules of hooks.&quot;</p><h3>4. Keep hooks pure at the top level</h3><p>A custom hook’s body runs on every render, just like a component. Avoid side effects directly in the function body, put them in <strong>useEffect</strong>.</p><pre>function useUser() {<br>  console.log(&quot;Custom hook is running&quot;);<br><br>  return {<br>    name: &quot;Hassnain&quot;,<br>  };<br>}<br><br>function App() {<br>  const [count, setCount] = useState(0);<br><br>  const user = useUser();<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;<br>      &lt;p&gt;{user.name}&lt;/p&gt;<br><br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increase<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>when component will render or re-render the custom hook also will run. Everytime component render the custom hook will render, so we avoid side effects(like api calls or setInterval or setTimeout etc) in custom hooks via useEffect.</p><pre><br>//Wrong practice<br>function useUser() {<br>  fetch(&quot;https://api.example.com/user&quot;)<br>    .then((response) =&gt; response.json())<br>    .then((data) =&gt; console.log(data));<br><br>  return null;<br>}<br><br>//Correct Practice<br><br>import { useEffect, useState } from &quot;react&quot;;<br><br>function useUser() {<br>  const [user, setUser] = useState(null);<br><br>  useEffect(() =&gt; {<br>    fetch(&quot;https://api.example.com/user&quot;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; {<br>        setUser(data);<br>      });<br>  }, []);<br><br>  return user;<br>}</pre><h3>5. Always clean up effects</h3><p>Especially critical in React Native, where listeners (NetInfo, AppState, Keyboard, BackHandler) keep firing after a component unmounts if you don’t remove them, a common source of memory leaks and “can’t perform a state update on an unmounted component” warnings.</p><pre>useEffect(() =&gt; {<br>  const subscription = NetInfo.addEventListener(state =&gt; {<br>    // handle state<br>  });<br>  return () =&gt; subscription(); // cleanup<br>}, []);</pre><h3>6. Use the ESLint plugin</h3><p>Install <strong>eslint-plugin-react-hooks</strong> and enable <strong>exhaustive-deps</strong>. It catches rule violations and missing dependencies automatically — don&#39;t rely on memory for this.</p><pre>npm install eslint-plugin-react-hooks --save-dev</pre><p>Real Life Example: <strong>useNetworkStatus</strong></p><pre><br>import { useState, useEffect, useRef } from &#39;react&#39;;<br>import NetInfo from &#39;@react-native-community/netinfo&#39;;<br><br>export function useNetworkStatus() {<br>  const [isConnected, setIsConnected] = useState(true);<br>  const [isInternetReachable, setIsInternetReachable] = useState(true);<br>  const [connectionType, setConnectionType] = useState(null);<br>  const wasOffline = useRef(false);<br><br>  useEffect(() =&gt; {<br>    const unsubscribe = NetInfo.addEventListener(state =&gt; {<br>      setIsConnected(state.isConnected);<br>      setIsInternetReachable(state.isInternetReachable);<br>      setConnectionType(state.type);<br><br>      // track reconnection so consumers can trigger a refetch<br>      if (!state.isConnected) {<br>        wasOffline.current = true;<br>      }<br>    });<br><br>    return () =&gt; unsubscribe();<br>  }, []);<br><br>  const justReconnected = isConnected &amp;&amp; wasOffline.current;<br><br>  useEffect(() =&gt; {<br>    if (justReconnected) {<br>      wasOffline.current = false;<br>    }<br>  }, [justReconnected]);<br><br>  return {<br>    isConnected,<br>    isInternetReachable,<br>    connectionType,<br>    isOffline: !isConnected,<br>    justReconnected,<br>  };<br>}</pre><p>Using It in a Screen</p><pre><br>import React, { useEffect } from &#39;react&#39;;<br>import { View, Text, FlatList, Banner } from &#39;react-native&#39;;<br>import { useNetworkStatus } from &#39;../hooks/useNetworkStatus&#39;;<br>import { useFeedData } from &#39;../hooks/useFeedData&#39;;<br><br>export default function FeedScreen() {<br>  const { isOffline, justReconnected } = useNetworkStatus();<br>  const { data, refetch } = useFeedData();<br><br>  useEffect(() =&gt; {<br>    if (justReconnected) {<br>      refetch(); // auto-refresh when connection comes back<br>    }<br>  }, [justReconnected]);<br><br>  return (<br>    &lt;View style={{ flex: 1 }}&gt;<br>      {isOffline &amp;&amp; (<br>        &lt;View style={{ backgroundColor: &#39;#ffcc00&#39;, padding: 8 }}&gt;<br>          &lt;Text&gt;You&#39;re offline. Showing cached content.&lt;/Text&gt;<br>        &lt;/View&gt;<br>      )}<br>      &lt;FlatList<br>        data={data}<br>        keyExtractor={item =&gt; item.id}<br>        renderItem={({ item }) =&gt; &lt;Text&gt;{item.title}&lt;/Text&gt;}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><h3>Why This Works Well</h3><ul><li><strong>FeedScreen </strong>doesn&#39;t know anything about<strong> NetInfo.</strong> If you swap the underlying library later, only <strong>useNetworkStatus.js </strong>changes.</li><li><strong>JustReconnected </strong>is derived, reusable logic<strong>, </strong>auto-refetching on reconnect is a pattern you&#39;ll want in multiple screens (feed, chat, profile sync), and now it&#39;s one line to add anywhere.</li><li><strong>The cleanup function</strong> prevents the classic React Native bug where NetInfo keeps calling setIsConnected on a screen the user has already navigated away from.</li></ul><p><strong>Conclusion</strong></p><p>Custom hooks in React Native aren’t a separate concept from React’s hooks, they’re the same rules, applied to your own reusable logic. The payoff is real: thinner components, logic you can test without a simulator, and patterns like useFetch, useNetworkStatus or useUploadPicture, that you write once and use across an entire app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06793daf3f47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Practice Variables (var,let,const)]]></title>
            <link>https://medium.com/@KhanHassnain/javascript-practice-variables-var-let-const-6d6dca332c53?source=rss-79158af197f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6dca332c53</guid>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Hassnain]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 10:02:26 GMT</pubDate>
            <atom:updated>2026-07-25T10:02:26.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>How this topic is organized</h3><p>For this topic, you’ll find:</p><ol><li><strong>Theory</strong></li><li><strong>Syntax (examples)</strong></li><li><strong>Dry Run (step-by-step execution)</strong></li><li><strong>Interview Questions (with answers)</strong></li><li><strong>Coding Problems (practice prompts)</strong></li></ol><h3>Part 1: Theory</h3><h4>What is a variable?</h4><p>A variable is a <strong>named container</strong> that stores a value in memory. You can use that value later in your program and (depending on how it’s declared) update it.</p><p>JavaScript has <strong>three</strong> ways to declare variables:</p><ul><li>var</li><li>let</li><li>const</li></ul><p>They differ mainly in:</p><ul><li><strong>Scope</strong> (where the variable can be accessed)</li><li><strong>Hoisting behavior</strong> (how declarations behave before execution reaches them)</li><li><strong>Re-assignability</strong> (whether you can give the variable a new value)</li></ul><h4>var (legacy, ES5 and earlier)</h4><ul><li><strong>Function-scoped</strong> (visible throughout the entire function)</li><li><strong>Not block-scoped</strong> (it “leaks” out of {} blocks like if/for)</li><li><strong>Hoisted</strong> and initialized as undefined</li><li><strong>Can be re-declared</strong> and <strong>re-assigned</strong></li><li>If declared globally in browsers, it becomes a property on window</li></ul><h4>let (ES6 / 2015)</h4><ul><li><strong>Block-scoped</strong> (only visible inside the {} block)</li><li><strong>Hoisted but not initialized</strong> (it exists in the <strong>Temporal Dead Zone (TDZ)</strong> until the declaration line runs)</li><li><strong>Cannot be re-declared</strong> in the same scope</li><li><strong>Can be re-assigned</strong></li></ul><h4>const (ES6 / 2015)</h4><ul><li><strong>Block-scoped</strong>, like let</li><li>Also has a <strong>TDZ</strong></li><li><strong>Cannot be re-declared</strong> or <strong>re-assigned</strong></li><li>Must be initialized at declaration</li><li>Important nuance: const prevents <strong>reassignment of the binding</strong>, but objects/arrays can still be <strong>mutated</strong></li></ul><h3>Quick comparison table</h3><p>Feature var let const Scope Function Block Block Hoisting Yes (initialized as undefined) Yes (TDZ) Yes (TDZ) Re-declare ✅ Yes ❌ No ❌ No Re-assign ✅ Yes ✅ Yes ❌ No Global object property (browser) ✅ Yes ❌ No ❌ No Must initialize at declaration ❌ No ❌ No ✅ Yes</p><h4>Why this matters</h4><p>Modern JavaScript generally follows:</p><ul><li>Use <strong>const by default</strong></li><li>Use <strong>let</strong> only when the value must change</li><li>Avoid <strong>var</strong> in modern code (but learn it for legacy code)</li></ul><h3>Part 2: Syntax (examples)</h3><pre>// --------------------<br>// var (function-scoped)<br>// --------------------<br>var name; // declared<br>console.log(name); // undefined (hoisted + initialized)</pre><pre>name = &quot;John&quot;;<br>console.log(name); // John</pre><pre>var name = &quot;Jane&quot;; // re-declaration is allowed<br>console.log(name); // Jane</pre><pre>function testVar() {<br>  var age = 30;</pre><pre>  if (age &gt; 20) {<br>    var isAllowed = true; // NOT block-scoped<br>  }</pre><pre>  console.log(age);       // 30<br>  console.log(isAllowed); // true<br>}</pre><pre>testVar();</pre><pre>// ------------------<br>// let (block-scoped)<br>// ------------------<br>let city;<br>console.log(city); // undefined (declared but not assigned yet)</pre><pre>city = &quot;New York&quot;;<br>console.log(city); // New York</pre><pre>// let city = &quot;LA&quot;; // ❌ SyntaxError: Identifier &#39;city&#39; has already been declared</pre><pre>// TDZ example (do not run as-is):<br>// console.log(age);<br>// let age = 25; // ReferenceError: Cannot access &#39;age&#39; before initialization</pre><pre>// -------------------<br>// const (block-scoped)<br>// -------------------<br>const PI = 3.14;<br>console.log(PI); // 3.14</pre><pre>const person = { name: &quot;Jane&quot;, age: 30 };<br>person.name = &quot;John&quot;; // ✅ allowed (mutation)<br>console.log(person.name); // John</pre><pre>// person = { name: &quot;Sara&quot; }; // ❌ TypeError: Assignment to constant variable</pre><h3>Part 3: Dry Run (step-by-step execution)</h3><p>Dry running means mentally tracing what happens in memory <strong>before</strong> and <strong>during</strong> execution. This is where var, let, and const behave very differently.</p><h4>Dry Run 1: var hoisting</h4><pre>console.log(a); // ?<br>var a = 5;<br>console.log(a); // ?</pre><p><strong>What actually happens (conceptually):</strong></p><p><strong>Phase 1 — Memory creation (hoisting):</strong></p><pre>var a; // hoisted and initialized as undefined</pre><p><strong>Phase 2 — Execution (line by line):</strong></p><ul><li>console.log(a) → undefined</li><li>a = 5</li><li>console.log(a) → 5</li></ul><p><strong>Output:</strong></p><pre>undefined<br>5</pre><h4>Dry Run 2: let and the Temporal Dead Zone (TDZ)</h4><pre>console.log(b); // ?<br>let b = 10;<br>console.log(b); // ?</pre><p>Even though b is hoisted, it’s not initialized until the declaration line runs. Accessing it before that throws:</p><p><strong>Output:</strong></p><pre>ReferenceError: Cannot access &#39;b&#39; before initialization</pre><h4>Dry Run 3: Function scope vs block scope</h4><pre>function testVar() {<br>  if (true) {<br>    var x = 1;<br>  }<br>  console.log(x); // ?<br>}<br>testVar();</pre><pre>function testLet() {<br>  if (true) {<br>    let y = 1;<br>  }<br>  console.log(y); // ?<br>}<br>testLet();</pre><p><strong>Output:</strong></p><pre>1<br>ReferenceError: y is not defined</pre><h4>Dry Run 4: var in loops + async callbacks (classic interview gotcha)</h4><pre>for (var i = 0; i &lt; 3; i++) {<br>  setTimeout(() =&gt; console.log(i), 0);<br>}</pre><p><strong>Output:</strong></p><pre>3<br>3<br>3</pre><p>Why? Because var i is one shared variable; by the time the callbacks run, the loop has finished and i === 3.</p><p>Now with let:</p><pre>for (let i = 0; i &lt; 3; i++) {<br>  setTimeout(() =&gt; console.log(i), 0);<br>}</pre><p><strong>Output:</strong></p><pre>0<br>1<br>2</pre><p>Because let creates a new binding for each loop iteration.</p><h4>Dry Run 5: const with objects</h4><pre>const user = { name: &quot;Ali&quot;, age: 20 };</pre><pre>user.age = 21;     // ✅ mutation is allowed<br>console.log(user); // ?</pre><pre>user = { name: &quot;Sara&quot;, age: 22 }; // ?</pre><p><strong>Output:</strong></p><pre>{ name: &#39;Ali&#39;, age: 21 }<br>TypeError: Assignment to constant variable.</pre><h3>Part 4: Interview Questions (with answers)</h3><h4>Q1) What’s the difference between var, let, and const?</h4><p><strong>Answer:</strong> The core differences are:</p><ul><li><strong>Scope</strong>: var is function-scoped; let/const are block-scoped.</li><li><strong>Hoisting</strong>: var is hoisted and initialized as undefined; let/const are hoisted but live in the <strong>TDZ</strong>.</li><li><strong>Reassignment</strong>: var and let can be reassigned; const cannot.</li></ul><h4>Q2) What is the Temporal Dead Zone (TDZ)?</h4><p><strong>Answer:</strong> The TDZ is the time between entering a scope and the point where a let/const declaration is executed. The variable exists but is not accessible; accessing it throws a ReferenceError.</p><h4>Q3) Predict the output</h4><pre>console.log(x);<br>var x = 5;</pre><p><strong>Answer:</strong> undefined (because var x is hoisted and initialized).</p><h4>Q4) Predict the output</h4><pre>console.log(y);<br>let y = 5;</pre><p><strong>Answer:</strong> ReferenceError: Cannot access &#39;y&#39; before initialization (TDZ).</p><h4>Q5) What will this print?</h4><pre>for (var i = 0; i &lt; 3; i++) {<br>  setTimeout(() =&gt; console.log(i), 100);<br>}</pre><p><strong>Answer:</strong> 3 3 3 (same i shared by all callbacks). Fix by using let or by capturing i in a function scope.</p><h4>Q6) Can you re-declare a let variable in the same scope?</h4><pre>let a = 1;<br>let a = 2;</pre><p><strong>Answer:</strong> No. This throws SyntaxError: Identifier &#39;a&#39; has already been declared.</p><h4>Q7) Is this valid?</h4><pre>const arr = [1, 2, 3];<br>arr.push(4);</pre><p><strong>Answer:</strong> Yes. const prevents reassignment (arr = ...), not mutation (push, editing elements, etc.).</p><h4>Q8) Why does var attach to the global object but let/const don’t? (browser)</h4><pre>var a = 1;<br>let b = 2;</pre><pre>console.log(window.a); // ?<br>console.log(window.b); // ?</pre><p><strong>Answer:</strong> window.a is 1, but window.b is undefined. Global var becomes a property on the global object; let/const are stored in a separate lexical environment.</p><h4>Q9) What happens here? (shadowing + block scope)</h4><pre>{<br>  let x = 10;<br>  {<br>    let x = 20;<br>    console.log(x); // ?<br>  }<br>  console.log(x); // ?<br>}</pre><p><strong>Answer:</strong> 20, then 10.</p><h4>Q10) Why is var considered problematic in modern JS?</h4><p><strong>Answer:</strong> It can leak out of blocks, has confusing hoisting behavior (returns undefined instead of throwing), and often causes bugs in loops with async callbacks.</p><h3>Part 5: Coding Problems (practice)</h3><ol><li>Rewrite a small script that uses var into let/const (use const by default).</li><li>Fix the “loop + setTimeout” problem so it prints 0 1 2.</li><li>Given an object declared with const, write code that updates a nested value safely (without reassigning the object).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6dca332c53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>