React

React


1) vanilla useEffect state tracking for "side effects" like APIs, event listeners, timers, and cleanup. Talk about the "ignore flag" cleanup pattern inside useEffect to drop stale promises when components unmount or dependencies change. Versus declarative, hook-based data-fetching library (like v4 TanStack Query  was React Query v1-3) useMutation auto receives isPending, isError and isSuccess flags. 

   useEffect fires asynchronously after the browser paints the screen to keep the application responsive. useLayoutEffect fires synchronously after DOM mutations but before the browser paints. Using useLayoutEffect blocks the paint loop, causing slight performance penalties, but it prevents visual layout flickers when calculating element dimensions or positions dynamically.  

2) export interface OrderRequest { ... fields ... } to keep DTO in synch. (Tools like TypeGen, NSwag, or Typewriter).

3) Q: Problem with lots of re-rendering.  A: React DevTools Profiler captures flamegraphs and ranked charts to find why re-rendering. 

 a) Instead of useState or onChange, you could switch to Uncontrolled Components or useRef. 

 b) Use useMemo for high-cost computational algorithms. Memoizes value.

 c) Use useCallback hook primarily when passing a function down as a prop to a child component optimized with React.memo. Don't do useCallback all the time. Memoizes a function so it isn’t recreated on every render.

4) Store JWTs securely in memory (not localStorage), utilize HTTP-only cookies for refresh tokens, and build an authorization wrapper component that inspects decrypted token claims.

5) Q: Problem with Prop-Heavy Elements. A: Split the component into a parent container and sub-components (e.g., Select, Select.Option, Select.Header).

6) useTransition and useDeferredValue allow you to split UI updates into urgent and non-urgent tasks without locking up the user interface.

7) React's Default Crash Behavior: As of React 16+, any unhandled runtime error anywhere in the component tree causes React to unmount the entire app structure, rendering a blank screen for the user.

8) React 19+ introduces native Actions and hooks like useActionState at form level and useFormStatus in child component. useFormStatus cannot see a form's status if it is called within the same component that renders the <form> tag. 

9) Legacy stack reconciler executed updates synchronously and recursively, blocking the main thread. Fiber introduces a virtual stack frame architecture that splits work into chunks. It supports Concurrent Features that allow React to pause, resume, or discard WIP renders based on priority lanes (e.g., user input vs. data fetching)

10) Context API is a DI tool, not a state management system.  Every consumer re-renders whenever the context value object shifts.  External Zustand/Redux Toolkit bypass the React tree context boundary, enabling granular component subscriptions without unnecessary re-renders. 

11) Avoid scroll event listeners.

12) React 19+ has React Server Components that execute strictly on the server, allowing direct access to databases, microservices, and file systems without client-side API calls. Dependencies used inside RSCs (like markdown parsers) are excluded from the JavaScript client bundle, significantly improve initial page load times.

13) React 19+ use hook differ from traditional hook rules? Unlike standard hooks, use can be called conditionally or inside loops. It natively unwraps Promises and Context objects on the fly, integrating directly with <Suspense> boundaries to pause rendering until data or configurations resolve.

14) How handle huge number of rows in grid - virtualized list - use React-Virtualized library. Know number of visible elements in window, pagination, position in list, scrolling and page up/down button event capture.

15) Debouncing (The Winner for Inputs): Waits for user to stop typing for X ms before firing. 

  Throttling (The Alternative): Guarantees a network execution at least once every X ms. While helpful for heavy real-time operations like window resizing or infinite scroll. Leads to messy UI redraws and excessive API strain inside search fields.

16) export function useAutocomplete - custom hook or Material UI or React Aria.

17) React updates the Virtual DOM. It compares changes using a diffing algorithm. Only the changed parts are updated in the real browser DOM.

18) React apps are built using components (small reusable pieces of UI). 
Functional components are preferred in modern React:

function Hello() { return <h1>Hello</h1> }

class Hello extends React.Component {
render() { return <h1>Hello</h1>; }
}

19) JSX = JavaScript + HTML-like syntax
const element = <h1>Hello React</h1>;

20) Properties (Props) = input to components (read-only data)
function Child(props) { return <p>Hello {props.name}</p>; }
function Parent() { return <Child name="Krishna" /> }

21) State = internal values
const [count, setCount] = useState(0);

22) 3 Phases of Class Components:
  Mounting
    constructor()
    componentDidMount()  -- API calls
  Updating
    componentDidUpdate()
  Unmounting
   componentWillUnmount() -- Cleanup

23) One-Way Data Flow
Data moves only top → down (parent → child)

24) Reconciliation is the process of comparing Virtual DOM with previous DOM and updating only differences. Improves performance by avoiding full re-render.

25) Controlled vs Uncontrolled Components
function ControlledInput() {
const [name, setName] = React.useState("");
return (
<input
value={name}
onChange={(e) =>
setName(e.target.value)}
/>

);
}

function UncontrolledInput() {
const inputRef = React.useRef();
const handleSubmit = () => { alert(inputRef.current.value); };
return (
<>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>

);
}

26) Map is a loop through a data array and dynamically render a list of JSX elements.
{items.map(item => <li key={item.id}>{item.name}</li>)}

27) React Fragments group multiple elements without extra div.
<>
<h1>Hi</h1>
<p>Hello</p>
</>

28) PureComponent prevents re-render if props/state didn’t change (shallow compare).
29) Memoization & React.memo() prevents re-rendering functional components if props are same.
30) Higher-Order Components = function that takes a component and returns a new component.
31) Context API shares data between components without prop drilling. Simple sharing.
32) Redux = predictable state + debugging + time travel
33) React hook version of reducer logic:   const [state, dispatch] = useReducer(reducer, initialState);
34) React Router handles page navigation without reloading the browser.
35) Static routing is routes defined upfront (e.g., backend frameworks)
Dynamic routing is routes rendered based on app state (React).
36) Lazy loading loads components only when needed to reduce initial load time.
37) "Code Splitting" breaks bundle into smaller chunks.
38) Suspense does lazy loading to show fallback UI.
39) Error Boundary catches JavaScript UI errors and prevents entire app crash.
40) React Events vs JS DOM Events 
onClick vs onclick
41) Portals allow rendering components outside root element.
42) Forward refs allow passing ref to child component.
43) Uncontrolled inputs using useRef where input value managed by DOM instead of React.
44) Server-Side Rendering generates HTML on server & sends to browser.
45) React = CSR (Client-Side Rendering) by default
Next.js = SSR (Server-Side Rendering) + SSG (Static Site Generation)
46) Hydration attaches React events to pre-rendered HTML from SSR to make interactive.
47) A React Node refers to any unit that can be rendered in React, such as an element, string, number, or null. A React Element is an immutable object that defines what should be rendered, typically created using JSX or React.createElement. A React Component is either a function or class that returns React Elements, enabling the creation of reusable UI components.
48) Stateless components in React are components that do not manage or hold any internal state. They simply receive data via props and render UI based on that data.
49) Stateful components in React are components that manage and hold their own internal state. Use this.state (in class components) or useState (in functional components). Can update state using event handlers or lifecycle methods. Handle logic and data management.


Architectural Suggestions

1. Enforce Module Boundaries via Barrel Files (index.ts)

     • Use an index.ts file at the root of every feature directory to act as its public API.

     • Only export what outside folders need to see

2. Clean Separation of State Concerns

       Server State: Use tools like TanStack Query (React Query) to cache and sync server data.

       Global UI State: Use ultra-lightweight tools like Zustand or Redux Toolkit for cross-cutting state (e.g., sidebar toggles, active themes)

       Local/Form State: Keep form lifecycles local to the component tree using custom hooks or React Hook Form. 

3. Strict Folder Colocation if only used by that file

4. Aggressive Code Splitting & Performance Optimization

5. Absolute Path Mapping

      "paths": {

            "@/app/*": ["src/app/*"],

            "@/features/*": ["src/features/*"],

            "@/shared/*": ["src/shared/*"]

}

6. Scalability with Monorepos


Typical React Directory Structure

src/

├── app/                      # Application-level configuration & entry points

│   ├── store/                # Global UI state (e.g., Redux, Zustand)

│   ├── providers/            # Top-level context providers (Theme, Auth, Query)

│   ├── routes/               # Routing map configuration

│   └── App.tsx               # Root component orchestration

│

├── features/                 # Self-contained domain modules (The Core Core)

│   ├── auth/                 # Authentication feature

│   │   ├── api/              # Feature-specific API endpoints / queries

│   │   ├── components/       # Feature-specific UI (LoginForm, AuthCard)

│   │   ├── hooks/            # Custom hooks used only inside auth

│   │   ├── types/            # TypeScript types unique to auth domain

│   │   └── index.ts          # Public API / barrel file mapping exposures

│   │

│   ├── dashboard/            # Dashboard feature

│   └── analytics/            # Analytics feature

│

├── shared/                   # Global, domain-agnostic building blocks

│   ├── components/           # Generic design system components (Button, Modal)

│   ├── hooks/                # Universal hooks (useDebounce, useLocalStorage)

│   ├── services/             # Centralized clients (Axios/Fetch interceptors)

│   ├── utils/                # Pure formatting/helper functions

│   └── types/                # Shared enterprise data schemas

Comments

Popular posts from this blog

Whitelabel Options

Free AI Tools

Await