📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're a .NET developer joining a team with a React frontend. Explain React's core ideas: components, props, state and hooks (useState, useEffect), how rendering and re-rendering work, and how a React app typically loads and saves data through an ASP.NET Core API.

React fundamentals for a backend .NET developer: function components, props vs state, the useState and useEffect hooks, the render cycle, and the usual patterns for calling an ASP.NET Core API.

Junior Theory Beginner aspnet-core frontend hooks react spa typescript

🎯 Key points

  • UI = f(state): components are functions that return JSX from props and state
  • Props flow down and are read-only; state is owned by one component and changed only through its setter
  • A state change schedules a re-render of that component and its children; React diffs and commits only DOM changes
  • useEffect synchronises with outside systems (fetch, subscriptions), needs correct dependencies and cleanup; StrictMode runs it twice in development
  • Data fetching: fetch in an effect with AbortController, or TanStack Query for caching and retries
  • Larger apps add React Router for navigation and a store (Zustand, Redux Toolkit) only for complex client-only state
  • The API returns JSON over HTTP; React never talks to the database and enforces no security on its own
  • React 19.x is current (19.3, September 2026); new projects start with Vite or a framework, not Create React App (deprecated February 2025)

⏱ 30-second answer

React builds the UI from components: plain functions that take props (read-only inputs from the parent) and hold state (data the component owns, changed only through a setter from useState). When state changes, React re-renders that component, compares the new output with the old one and updates only the DOM nodes that changed, so the UI is always a function of state.

Hooks add behaviour to function components: useState for state, useEffect to synchronise with things outside React such as a network call or a timer, and custom hooks to reuse that logic.

A React app talks to an ASP.NET Core API with fetch (or a library like TanStack Query) returning JSON. React is only the client: validation, authorisation and data rules still live on the server. The trade-off is flexibility and a huge ecosystem against having to choose routing, data fetching and forms yourself.

🗣 Full answer (senior)

How I would answer this in an interview

"The way I explain React to other .NET developers is that it's a function from state to UI. A component is just a TypeScript function that returns JSX, which is markup compiled into JavaScript calls. It receives props from its parent, which are read-only, a bit like constructor arguments for a record, and it can hold state with the useState hook. You never mutate state directly; you call the setter, React schedules a re-render, runs the function again, diffs the result against the previous output and commits only the DOM changes. So instead of writing 'find this element and change its text', you change the data and let React work out the DOM.

For anything outside React, such as calling my API, I use useEffect. The effect runs after the render is committed, and its dependency array decides when it runs again. In practice I write a small custom hook, say useOrders(customerId), that calls fetch against the ASP.NET Core endpoint, passes an AbortController signal and aborts in the cleanup function, so a fast-typing user doesn't get an old response overwriting a new one. On bigger apps I'd rather use TanStack Query, which gives caching, de-duplication and retries without hand-written effects.

The mistake I see from backend developers is treating useEffect like an event handler or a constructor: fetching in it with a missing dependency, setting state that triggers the same effect in a loop, or forgetting cleanup, which StrictMode exposes by running effects twice in development. The other mistake is trusting the client. React decides what to show; the API decides what's allowed."


The core concepts mapped to .NET

React What it is Closest .NET idea
Component Function returning JSX A Razor component or partial view
Props Read-only inputs from parent Constructor parameters / [Parameter]
State (useState) Data owned by one component A private field that triggers a re-render
useEffect Sync with outside systems after render OnAfterRenderAsync + IDisposable
Custom hook (useX) Reusable stateful logic A small service injected into a component
Context Value shared down the tree Cascading value / scoped service

How a render works

Step What happens
Trigger Initial mount, or a state setter is called
Render React calls the component function and gets a new element tree
Reconcile It compares the new tree with the previous one (keys matter in lists)
Commit Only changed DOM nodes are updated; then effects run

Talking to the API

Approach When it fits When not
fetch in a custom hook Small apps, a few calls Many screens sharing cached data
TanStack Query Most line-of-business apps: caching, retries, invalidation Tiny widgets
Framework loaders (React Router, Next.js) Server rendering or route-level data A pure SPA on a static host

As of November 2026 the current release is React 19.3. New projects use Vite or a framework; Create React App was deprecated in 2025.

Production example

On an internal claims screen, replacing ad-hoc useEffect fetches with a useClaims hook built on TanStack Query cut duplicate API calls per page load from about 6 to 2 and removed a race where a slow response for an old filter overwrote the new results.

🔍 What the interviewer is checking

Checks whether a backend developer understands React's mental model well enough to read, review and safely change frontend code that calls their API.

Green flags

  • Explains UI as a function of state and how a state change leads to a re-render and a DOM diff
  • Distinguishes props (read-only, from parent) from state (owned, changed via setter)
  • Uses useEffect with correct dependencies and cleanup, and mentions AbortController or TanStack Query
  • States that authorisation and validation remain in the API
  • Knows current tooling (Vite; CRA deprecated)

Red flags

  • Describes manipulating the DOM directly with document.getElementById inside React
  • Thinks useEffect is a constructor or an event handler
  • Believes hiding UI elements secures an action
  • Cannot say why keys are needed in lists

📚 Learn in depth

1. JSX is just function calls

JSX such as <OrderRow order={o} /> compiles to jsx(OrderRow, { order: o }). The result is a plain object describing what should be on screen, not a DOM node. That is why React can call your component as often as it likes: rendering is cheap and has no side effects if you write it correctly.

state change ──► render (call function) ──► element tree
                                              │
                       previous tree ──► reconcile (diff)
                                              │
                                         commit DOM changes ──► run effects

2. State is a snapshot

Each render sees its own copy of state. Calling setCount(count + 1) twice in the same handler still adds one, because both calls read the same snapshot. Use the updater form setCount(c => c + 1) when the new value depends on the old one. React batches several setter calls into one render.

State must be treated as immutable: create a new array ([...items, newItem]) instead of items.push(newItem), because React compares references to decide whether something changed.

3. Props and lifting state up

Data flows down through props; events flow up through callback props (onSave). When two siblings need the same data, move the state to their closest common parent. For data needed far down the tree (the signed-in user, the theme), use Context, but sparingly, because every consumer re-renders when the value changes.

4. Effects and their lifecycle

useEffect(fn, deps) runs after the commit. The function may return a cleanup, which React runs before the next effect and on unmount.

  • []: run once after mount (twice in development under StrictMode, which mounts, unmounts and remounts to expose missing cleanup).
  • [customerId]: run again when customerId changes.
  • No array: run after every render, which is almost never what you want.

If you can compute something from props or state during render, do not put it in an effect and a second state variable.

5. Keys and lists

When rendering a list, give each item a stable key (the database id). Without it, or with the array index, React may reuse the wrong DOM node and input values jump between rows after a delete.

6. Where React stops

React runs in the user's browser. Anything it hides can still be called directly against the API, so authorisation, validation and business rules live in ASP.NET Core. The API returns DTOs; the browser renders them.

Try it yourself

  1. Create a project with npm create vite@latest orders -- --template react-ts and render a list from a hard-coded array.
  2. Add a counter and call the setter twice in one click with and without the updater form; observe the difference.
  3. Fetch from a Minimal API in useEffect, then remove the cleanup and watch StrictMode fire two requests in the Network tab.
  4. Render a list using the index as the key, delete the first row while an input is focused, and see the state jump; fix it with the id.
  5. Install React DevTools and use the Profiler to see which components re-render when one piece of state changes.

💻 Code

A Minimal API endpoint and the React component that loads from it, with cancellation in the effect cleanup.

// Program.cs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/api/orders", (string? status) =&gt;
{
    OrderDto[] orders =
    [
        new(1, "ACME Pty Ltd", 120.50m, "Open"),
        new(2, "Bondi Bikes", 89.00m, "Shipped"),
    ];
    return TypedResults.Ok(status is null ? orders : orders.Where(o =&gt; o.Status == status).ToArray());
});

app.Run();

public sealed record OrderDto(int Id, string Customer, decimal Total, string Status);
// src/OrderList.tsx
import { useEffect, useState } from "react";

type Order = { id: number; customer: string; total: number; status: string };

// Props are read-only inputs from the parent.
export function OrderList({ status }: { status?: string }) {
  // State owned by this component; changing it triggers a re-render.
  const [orders, setOrders] = useState

⚠ Common mistakes

  • Mistake: Mutating state directly (orders.push(x); setOrders(orders)). Why it is wrong: React compares references, sees the same array and may skip the re-render. Instead: Create a new array or object: setOrders([...orders, x]).
  • Mistake: Leaving the dependency array incomplete to stop an effect re-running. Why it is wrong: The effect reads stale props and state, causing subtle bugs. Instead: List every value the effect uses (the react-hooks ESLint rule enforces this) and restructure the code if it runs too often.
  • Mistake: Fetching in an effect without cleanup. Why it is wrong: A slow old response can overwrite a newer one, and StrictMode fires the request twice. Instead: Use an AbortController and abort in the cleanup, or use TanStack Query.
  • Mistake: Copying props into state (useState(props.order)). Why it is wrong: The state is initialised once and then drifts from the prop. Instead: Read the prop directly, or derive values during render.
  • Mistake: Using the array index as a key. Why it is wrong: After inserts or deletes React reuses the wrong elements and their state. Instead: Use a stable id from the data.
  • Mistake: Hiding a button and assuming the action is protected. Why it is wrong: Anyone can call the API directly. Instead: Enforce authorisation in ASP.NET Core with policies; the UI only mirrors it.
  • Mistake: Starting a new app with Create React App. Why it is wrong: It was deprecated in 2025 and is unmaintained. Instead: Use Vite, or a framework such as React Router or Next.js if you need server rendering.

🏛 Senior insight: trade-offs

React is a rendering library, not a framework. That is its strength and its cost: a .NET team must choose routing, data fetching, forms and state management, and those choices matter more for long-term maintenance than React itself. For line-of-business apps I standardise early on Vite + TypeScript + React Router + TanStack Query + a form library, and I generate the API client from OpenAPI so the frontend breaks at compile time when a DTO changes. A global store such as Zustand or Redux Toolkit is only added when there is genuinely complex client-only state; server data belongs in the query cache.

Also be honest about what the backend still owns: every rule the UI shows (required fields, allowed actions) must be enforced again in the API, and the UI should render the server's ProblemDetails errors rather than duplicating validation logic it can drift from. Note on versions (checked November 2026): React 19.3 is the current release, and Create React App was officially deprecated in February 2025, so new projects should not use it.

Data approach When it fits Cost When not to
Hand-written fetch hooks Small app, few endpoints Re-implementing caching and retries Many screens share data
TanStack Query Most CRUD and dashboard apps One dependency, cache invalidation to learn Offline-first apps needing a local database
Global store (Redux Toolkit, Zustand) Complex client-only state (editors, wizards) Boilerplate, extra concepts Server data; use a query cache instead
Navigation When it fits When not to
React Router (library mode) Classic SPA on a static host or behind ASP.NET Core You need server rendering for SEO
React Router framework mode / Next.js Server rendering, route-level data loading The team wants a pure static SPA with a separate API

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions calling the API with fetch from an effect. Why: Checks error handling, ProblemDetails and AbortController in real fetch code.
    How to answer

    Wrap fetch once. Send JSON with method, a Content-Type: application/json header and JSON.stringify(body). Remember fetch only rejects on network errors or abort: a 400 or 500 resolves normally, so always check response.ok. On failure, if the content type is application/problem+json, parse the ProblemDetails (title, status, detail, and for validation an errors dictionary keyed by field) and throw a typed error the UI can map to form fields. For cancellation create an AbortController, pass its signal, and call abort() when the component unmounts or a newer search starts; combine with AbortSignal.timeout() for a deadline and ignore AbortError. On the server, ASP.NET Core binds a CancellationToken to RequestAborted, so the database query stops too. The trade-off: a small wrapper is enough; reach for a library only when you need caching and retries.

  2. When: Candidate writes the component in TypeScript. Why: Checks whether they understand TypeScript's structural types and type erasure compared with C#.
    How to answer

    JavaScript is dynamically typed and runs on a single-threaded event loop, unlike C#'s thread pool. TypeScript adds a static, structural type system on top, checked by tsc, then erased: at run time it's plain JavaScript, so a type annotation on a fetch result is a promise to the compiler, not a check, and API responses must be generated from the contract or validated (e.g. with zod). Compared with C#: types match by shape, not by name; there are two empties, null and undefined; numbers are all 64-bit floats; and you compare with ===. async/await looks identical to C#, but a Promise always resumes on the main thread, there is no ConfigureAwait and no blocking .Result. Code is organised as ES modules with import/export, packages come from npm. The trade-off: TypeScript gives C#-like tooling, but the safety stops at the network boundary.

  3. When: Candidate mentions a data-fetching library or caching on the client. Why: Checks whether they understand server-state caching, de-duplication and invalidation.
    How to answer

    TanStack Query treats API data as server state: it caches responses by a query key, de-duplicates identical requests, retries failures, refetches stale data on window focus or reconnect, supports polling (refetchInterval) and paginated / infinite queries (placeholderData: keepPreviousData, useInfiniteQuery), and lets you invalidate keys after a mutation so lists refresh. Hand-written useEffect fetches repeat all of that per screen and usually get races and cleanup wrong, so the library mostly buys developer time and fewer bugs.

    Use plain fetch for one or two calls; use TanStack Query once several screens share data, you page through large lists, or you need optimistic updates. It does not replace the API's own HTTP caching or authorisation.

↩ Usually asked after

More in SPA Integration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me