React JS Complete Guide 2026: Beginner to Master
The only React JS guide you need in 2026. Master components, hooks, state management, performance, React 19, and more - with 200+ interview questions and real code examples.
React JS Complete Guide
Beginner to Master (with 200+ Interview Questions)
"You can't master React Native without first mastering React. This is the guide I wish existed when I started."
In 2026, React continues to dominate the web development landscape. Powering over 11 million active websites and commanding a 42% adoption rate among professional developers, React's ecosystem is stronger than ever. The release of React 19 has solidified its position by introducing compiler-driven optimizations and native server-side capabilities that eliminate years of boilerplate.
As a developer, my own journey with React Native made one thing abundantly clear: your mobile apps are only as solid as your web fundamentals. The virtual DOM, state synchronization, component lifecycles, and hook behaviors are identical across both environments. Mastering React isn't just about building web applications; it is the absolute foundation for cross-platform mastery.
Why This Guide Exists
Prerequisites
- JavaScript ES6+: Comfort with arrow functions, destructuring, and array methods.
- Basic HTML & CSS: Understanding of semantic layouts and styling paradigms.
- Terminal & Node.js: Familiarity with running package scripts (`npm`, `npx`).
Quick Navigation Index
Section 1: JavaScript Prerequisites for React
Target Keyword: javascript concepts for react
Before diving into React, mastering modern JavaScript (ES6+) is non-negotiable. React is not a new language; it is standard JavaScript syntax augmented with JSX. Under the hood, state updates, component layouts, and side effects rely heavily on language-level features like closures, lexical scoping, asynchronous event loops, and array manipulations.
Core Concepts Covered
- Arrow Functions & Lexical `this`: Simplifying event handling and scoping.
- Destructuring & Spread/Rest Operators: Efficient prop extraction and state copying.
- Template Literals: Dynamically injecting variables into UI strings.
- Array Methods: Transforming lists using `.map()`, `.filter()`, and `.reduce()`.
- ES6 Modules: Component scoping via standard `import` and `export`.
- Promises & Async/Await: Asynchronous remote data fetching pipelines.
- Optional Chaining & Nullish Coalescing: Guarding against runtime errors with `?.` and `??`.
Code Examples
// Regular function syntax (requires manual binding in class components)
function clickHandlerRegular() {
console.log(this); // 'this' depends on invocation context
}
// Arrow function syntax (lexically binds 'this' of parent scope)
const clickHandlerArrow = () => {
console.log(this); // 'this' is preserved lexically
};// Destructuring props directly inside function signature
const UserProfile = ({ username, role = "Developer", status }) => {
return (
<div className="p-4 rounded border">
<h2>{username}</h2>
<p>Role: {role}</p>
<span>Status: {status}</span>
</div>
);
};// Rendering lists using .map()
const ItemList = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};// Asynchronous data fetching with async/await and error handling
const fetchUserData = async (userId, signal) => {
try {
const response = await fetch(`https://api.example.com/users/${userId}`, { signal });
if (!response.ok) {
throw new Error("Network response was not OK");
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === "AbortError") {
console.log("Fetch aborted");
} else {
console.error("Fetch failed: ", error);
}
throw error;
}
};🎯 Section 1 Interview Questions (10+)
1. What is the difference between var, let, and const?
var is function-scoped, hoisted (initialized as undefined), and can be redeclared. let and const are block-scoped, hoisted but kept in the Temporal Dead Zone (TDZ) until evaluation, and cannot be redeclared. const forbids re-assignment of the variable identifier itself, although properties of objects assigned to const can still be mutated.
2. How does destructuring work and why is it used heavily in React?
Destructuring allows unpacking values from arrays or properties from objects into distinct variables. In React, it is heavily used to extract props directly in functional component signatures and to unpack state and state setters returned by the useState hook.
3. What is the spread operator and how is it used with props?
The spread operator (...) spreads the contents of an object or array. In React, it's used to forward all props from a parent component directly to a child component (e.g., <Child {...props} />), though this pattern should be used selectively to avoid passing unneeded attributes.
4. Explain Promise vs async/await with a fetch example.
Promises handle asynchronous actions using callback chaining (.then().catch()). async/await is syntactic sugar over Promises, making async code write and read like synchronous code. It uses try/catch blocks for clean error handling.
5. What is optional chaining and when would you use it in a React component?
Optional chaining (?.) reads nested properties of an object without throwing a ReferenceError if a reference is nullish (null or undefined). You would use it when rendering data from async API responses that might not be fully loaded yet (e.g., user?.address?.street).
6. What are arrow functions and how do they handle 'this' differently?
Arrow functions do not have their own 'this' binding. They lexically capture the 'this' value of their surrounding execution context. This eliminates the need to call .bind(this) on event handler methods in React class components.
7. What is the difference between named and default exports?
Default exports export a single primary resource from a file (e.g., export default Component) and can be imported under any name without curly braces. Named exports export multiple resources from a single file (e.g., export { ComponentA, ComponentB }) and must be imported using curly braces matching the exact exported name.
8. What does .map() return and why is it used to render lists?
.map() transforms an array by applying a callback function to each item, returning a new array. It is used in React because JSX can render arrays of elements directly, mapping raw data to JSX elements.
9. How does template literal differ from string concatenation?
Template literals use backticks (`) and allow embedded expressions (${expression}) and multi-line strings directly, whereas string concatenation uses '+' which is harder to read and maintain for complex dynamic strings.
10. What is the nullish coalescing operator (??) and how does it differ from ||?
The ?? operator returns the right-hand operand only if the left-hand operand is null or undefined. The logical OR (||) operator returns the right-hand operand for any falsy value (e.g., '', 0, false), which can cause bugs in React when 0 or false are valid UI values.
11. Explain closures and give an example relevant to React hooks.
A closure is the combination of a function bundled together with references to its surrounding state (lexical environment). React hooks like useEffect and useCallback close over variables (props, state) from the render cycle in which they were defined. If dependency arrays are omitted or configured incorrectly, it can lead to 'stale closures' where hooks reference outdated variables.
12. What is the event loop and why does it matter in React's async patterns?
The JavaScript event loop manages asynchronous tasks. It executes code, collects and processes events, and runs queued sub-tasks (macro-tasks like setTimeout and micro-tasks like Promise resolutions). It matters in React because state updates are batched asynchronously, executing after the call stack clears to optimize rendering performance.
Section 2: React Fundamentals - What is React?
Target Keyword: what is react js 2026
At its core, React is a declarative, component-based JavaScript library for building user interfaces. React's primary innovation is the separation of state representation from DOM mutations. By expressing the UI as a pure function of state, React eliminates the error-prone manual DOM manipulations of the past.
Virtual DOM vs Real DOM
Updating the Real DOM is slow because it requires layout recalculations, CSS reflows, and repaints. React avoids this bottleneck by maintaining a lightweight in-memory representation of the DOM tree: the Virtual DOM.
State Change
User clicks button, updates state variable
Virtual DOM Re-render
React builds a new Virtual DOM tree representing updated state
Diffing & Reconcile
Fiber engine compares trees, compiles minimal changes, updates Real DOM
Code Examples
// Simple Hello World structure
import React from 'react';
import { createRoot } from 'react-dom/client';
const App = () => {
return <h1>Hello World from React 19!</h1>;
};
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);// JSX Representation
const elementJSX = <h1 className="title">Hello World</h1>;
// Compiled equivalent (using plain React.createElement)
const elementPlain = React.createElement(
'h1',
{ className: 'title' },
'Hello World'
);// Conceptual representation of a Virtual DOM Node
const vNode = {
type: 'div',
props: {
className: 'container',
children: [
{ type: 'h1', props: { children: 'Virtual DOM Demo' } }
]
}
};🎯 Section 2 Interview Questions (10+)
1. What is React and how does it differ from a framework like Angular?
React is an open-source, component-based UI library focused strictly on the View layer of an application. Angular is a full-featured MVC framework that provides out-of-the-box solutions for routing, state management, form validation, and HTTP requests. React offers more architectural flexibility, relying on its ecosystem for secondary capabilities.
2. What is the Virtual DOM and how does it improve performance?
The Virtual DOM is a lightweight JavaScript representation of the Real DOM. When state changes, React updates the Virtual DOM first. It then compares this updated tree with the previous Virtual DOM tree (a process called diffing) to find the minimum number of changes needed, executing only those specific modifications to the Real DOM, which prevents expensive layout reflows.
3. Explain the reconciliation process in React.
Reconciliation is the algorithm React uses to diff the Virtual DOM trees and update the UI. It operates on an O(N) heuristic based on two assumptions: (1) two elements of different types will produce different trees, and (2) child elements can be marked as stable across renders using a unique key prop.
4. What is React Fiber and what problem does it solve?
React Fiber is the complete rewrite of React's core reconciliation algorithm introduced in React 16. It solves the limitation of synchronous rendering, which blocked the main thread on large trees. Fiber enables incremental rendering, allowing React to pause, abort, or reuse rendering work to prioritize high-priority updates (like animations or user inputs).
5. What is the difference between declarative and imperative programming?
Imperative programming requires writing step-by-step instructions telling the browser *how* to update the DOM (e.g., document.createElement, appendChild). Declarative programming describes *what* the UI should look like based on the current state, and the library (React) handles updating the DOM to match that description.
6. What is JSX? Is it required in React?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows writing HTML-like tags within a JavaScript file. It is not strictly required-you can write plain React.createElement() calls-but it is highly recommended because it improves readability and developer experience.
7. What does ReactDOM.render() do? What replaced it in React 18+?
ReactDOM.render() mounted a React component tree to a specific DOM node in React 17 and below. In React 18 and 19, it was deprecated and replaced by createRoot(), which enables concurrent features by initializing the rendering pipeline under the new concurrent scheduler.
8. What are the major changes introduced in React 19?
React 19 introduced the React Compiler (automatic memoization, eliminating useMemo and useCallback), React Actions (async transitions for form states), the use() hook (to resolve promises and consume context inline), direct support for document metadata tags (title, meta), and automatic ref forwarding without forwardRef.
9. What is the React Compiler and how does it change development?
The React Compiler (formerly React Forget) is a build-time compiler that analyzes React code and automatically injects memoization logic. It ensures that components and values only re-render when their dependencies actually change, saving developers from manually writing useMemo, useCallback, or React.memo.
10. Why does React use a one-way data flow?
One-way data flow (or unidirectional data flow) means data flows in a single direction: down from parent components to children via props. This constraint makes the app more predictable, easier to debug, and simpler to reason about, as data mutations are localized to specific components.
11. What is StrictMode in React and when should you use it?
StrictMode is a development-only tool that highlights potential problems in an application. It triggers intentional double-rendering of components to check for side effects, alerts you about legacy API usage, and flags memory leaks. It should wrap the root component during development.
12. What is the difference between React, ReactDOM, and React Native?
React is the core library containing the component blueprint, state lifecycle, and hooks. ReactDOM is the renderer specifically for web browsers, mapping components to DOM nodes. React Native is the renderer for mobile apps, mapping React components to native iOS and Android UI elements.
Section 3: Components - The Building Blocks
Target Keyword: react components explained 2026
Components are the primary structural building blocks of a React application. They allow you to partition the user interface into independent, reusable, and isolated pieces. By conceptualizing the UI as a tree of component nodes, you can compose highly complex applications from simple, self-contained widgets.
Functional vs Class Components
Historically, Class components were required to manage state and lifecycle hooks. Since React 16.8 and the introduction of React Hooks, Functional components have become the modern industry standard. They are simpler, compile to less boilerplate, and optimize better under compiler systems.
Code Examples
// Modern Functional Component syntax
import React from 'react';
const ProfileCard = ({ name, bio }) => {
return (
<div className="profile-card">
<h3>{name}</h3>
<p>{bio}</p>
</div>
);
};
export default ProfileCard;// Legacy Class Component syntax (kept for reference and interview prep)
import React, { Component } from 'react';
class LegacyProfileCard extends Component {
render() {
const { name, bio } = this.props;
return (
<div className="profile-card">
<h3>{name}</h3>
<p>{bio}</p>
</div>
);
}
}
export default LegacyProfileCard;// Composing parents and children
const Header = () => <header><h1>My Dashboard</h1></header>;
const Footer = () => <footer>© 2026</footer>;
const PageLayout = () => {
return (
<div className="layout">
<Header />
<main>
<p>Main content goes here.</p>
</main>
<Footer />
</div>
);
};// Reusable wrapper using the 'children' prop
const Modal = ({ isOpen, children }) => {
if (!isOpen) return null;
return (
<div className="modal-overlay">
<div className="modal-content">
{children}
</div>
</div>
);
};
// Usage:
// <Modal isOpen={true}>
// <h2>Login</h2>
// <input type="text" placeholder="Username" />
// </Modal>// Fragment usage to return adjacent elements without wrapper div
const TableRow = () => {
return (
<React.Fragment>
<td>Name</td>
<td>Email</td>
</React.Fragment>
);
};
// Short syntax:
const ShortTableRow = () => {
return (
<>
<td>Name</td>
<td>Email</td>
</>
);
};🎯 Section 3 Interview Questions (10+)
1. What is the difference between a functional and a class component?
Functional components are plain JavaScript functions that accept props as arguments and return JSX. Class components are ES6 classes that extend React.Component, requiring a render() method and managing state via this.state. Functional components are preferred due to Hooks, shorter syntax, and better performance.
2. Why are functional components preferred in 2026?
Functional components are cleaner, require less boilerplate, and facilitate code sharing via custom Hooks. With React 19's compiler, functional code can be automatically optimized, which is much harder to achieve with Class components due to complex lexical binding.
3. What are the JSX syntax rules? What are common mistakes?
JSX rules: (1) must return a single root element or Fragment, (2) tags must be explicitly closed, (3) JavaScript values in JSX must be wrapped in curly braces {}, and (4) HTML attributes must use camelCase (e.g., class becomes className, onclick becomes onClick). Common mistakes include leaving elements unclosed or returning multiple root-level sibling nodes.
4. What is a Fragment and why use it instead of a wrapper <div>?
A Fragment (<React.Fragment> or <></>) wraps multiple adjacent sibling elements without adding an extra node to the real DOM. This maintains correct HTML structure (crucial for grid, flexbox, or tables) and keeps the DOM tree shallow.
5. What is the children prop and how is it used?
The children prop is a special prop passed automatically to every component. It contains whatever JSX is written between the component's opening and closing tags. It enables container components to render dynamic child content (composition).
6. Can a React component return null? When would you do this?
Yes, a component can return null. React will render nothing in its place. This is used for conditional rendering, such as hiding overlays, modals, banners, or tooltips when their display conditions are not met.
7. What is component composition and why is it preferred over inheritance?
Component composition is the practice of building components by nesting other components or using children. React's official model recommends composition because it provides maximum flexibility. Component inheritance creates deep hierarchies that make code sharing rigid and fragile.
8. How do you name React components and why does casing matter?
React components must be named in PascalCase (e.g., UserCard, Sidebar). This casing is critical because React uses it to distinguish custom components from built-in HTML tags (which are written in lowercase, e.g., <div>, <span>).
9. What happens if you return multiple elements without a wrapper in JSX?
It will throw a syntax compilation error. The JSX compiler converts tags into React.createElement() calls. A function cannot return multiple separate function calls at the top level, so they must be enclosed within a single parent node or Fragment.
10. What is the difference between a component and an element in React?
A React element is a plain JavaScript object describing what you want to see on screen (returned by React.createElement()). A React component is a function or class that optionally accepts input (props) and returns a React element tree.
11. What does 'lifting state up' mean?
'Lifting state up' is the practice of moving state variables to the closest common ancestor of components that need to share that data. This allows parent components to control child states via props.
12. What is the difference between controlled and uncontrolled components?
Controlled components have their form data managed by React state, synced via value and onChange props. Uncontrolled components store their form data directly in the DOM, accessed when needed using Refs.
Section 4: Props - Passing Data Down
Target Keyword: react props explained
Props (short for "properties") are read-only inputs passed from a parent component down to a child component. In React's unidirectional data flow model, props represent configuration parameters that customize how children render and behave.
Core Attributes of Props
- Immutability: A component must never modify its own props. They are read-only from the child's perspective.
- Data Variety: You can pass strings, numbers, booleans, arrays, objects, functions, or even entire JSX elements as props.
- Unidirectional Flow: Data travels strictly downwards, which makes predicting application flow much simpler.
Code Examples
// Parent passing dynamic variables and functions to a child
const Dashboard = () => {
const handleAlert = (msg) => alert(msg);
return (
<div className="p-8">
<WelcomeBanner
username="Dev"
age={28}
isAdmin={true}
tags={['react', 'web']}
onAlert={handleAlert}
/>
</div>
);
};// Best practice: default props via ES6 destructuring parameters
const WelcomeBanner = ({ username, age = 18, isAdmin = false, onAlert }) => {
return (
<div className="banner">
<h1>Welcome back, {username}!</h1>
<p>Age: {age} {isAdmin && "(Admin Access)"}</p>
<button onClick={() => onAlert("Hello from banner")}>Trigger Alert</button>
</div>
);
};// Runtime type checking via PropTypes (legacy, preferred is TypeScript)
import PropTypes from 'prop-types';
const UserBadge = ({ label, level }) => {
return <span className={`badge-${level}`}>{label}</span>;
};
UserBadge.propTypes = {
label: PropTypes.string.isRequired,
level: PropTypes.oneOf(['bronze', 'silver', 'gold']).isRequired
};// Visualizing prop drilling: forwarding props down multiple levels
const TopComponent = () => {
const [theme] = React.useState("dark");
return <MiddleComponent theme={theme} />;
};
const MiddleComponent = ({ theme }) => {
// Theme is unused here, only forwarded
return <BottomComponent theme={theme} />;
};
const BottomComponent = ({ theme }) => {
return <div className={`box theme-${theme}`}>Styled Content</div>;
};🎯 Section 4 Interview Questions (10+)
1. What are props in React? Are they mutable?
Props (properties) are read-only configuration inputs passed from a parent component to a child. They are immutable. A child component must never modify the props it receives; changing props violates React's pure-function component design.
2. How is data flow different between props and state?
Props represent external configuration data received from a parent, which are read-only and trigger renders when changed by the parent. State represents internal, private, and mutable data managed locally inside the component itself.
3. What is prop drilling and why is it a problem?
Prop drilling is the process of passing props through multiple levels of intermediate components that don't need the data, simply to reach a deeply nested child component. It creates highly coupled, hard-to-maintain components and clutters component APIs.
4. How do you set default values for props?
The modern standard in functional components is to use ES6 default parameter syntax directly in the function signature (e.g., const MyComponent = ({ title = 'Default' }) => ...). Historically, components used MyComponent.defaultProps = {}.
5. What is PropTypes and when would you use it over TypeScript?
PropTypes is a runtime type-checking library. TypeScript performs compile-time static type-checking. TypeScript is generally preferred because it catches errors before run-time without adding bundle overhead. You would use PropTypes if you are maintaining a legacy JavaScript application or building a library that needs runtime validation.
6. How do you pass a function as a prop and why is this pattern useful?
You pass a function by reference (e.g., <Button onClick={handleClick} />). This is useful because it allows a child component to trigger logic inside the parent component, enabling child-to-parent communication.
7. What is the key prop? Why does React require it in lists?
The key prop is a special string attribute you must include when rendering lists of elements. React uses keys during the reconciliation process to identify which items have changed, been added, or been removed, optimizing DOM updates.
8. What happens when you use index as key in a list?
Using the array index as a key can cause rendering errors and state bugs if the list is sorted, filtered, or items are added/deleted. React assumes item identity based on key, so swapping index positions can map local states (like inputs) to the wrong list elements.
9. Can you modify props inside a component? What happens if you try?
No, modifying props directly causes a TypeError in strict mode or causes silent bugs because React will not track the mutation and will not trigger a re-render. Always treat props as read-only constants.
10. How do you spread props onto a component?
You spread props using the JSX spread operator: <Child {...props} />. This passes all key-value pairs of the props object as separate props. Use it carefully, as it can pass redundant or invalid HTML attributes down.
11. What is the difference between props.children and regular props?
Regular props are passed as named attributes (e.g., title='Home'). props.children is a special, automatically populated prop containing the elements nested between the opening and closing tags of the component.
12. How would you pass data from child to parent in React?
You pass data by invoking a callback function received as a prop from the parent. The child calls the function and passes the data as an argument, which the parent then receives and processes (e.g., updating its own state).
Section 5: State - Making Components Dynamic
Target Keyword: react state management useState
State is a built-in object that allows React components to store, modify, and track their own local, dynamic data. Unlike props, which are configuration values passed into a component from its parent, state is private, internal, and completely controlled by the component itself.
The Rule of Immutability
React relies on reference changes to detect state mutations and trigger re-renders. If you mutate state directly (e.g., state.value = 10), React cannot notice the change, resulting in frozen UIs. You must always construct new arrays or objects when updating complex states.
Code Examples
// Counter showing standard useState and functional updates
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
// Bad if multiple updates are queued: setCount(count + 1);
// Good: Functional updates guarantee latest prev state
setCount((prev) => prev + 1);
};
return (
<div className="flex gap-4 items-center">
<span>Count: {count}</span>
<button onClick={increment}>Add</button>
</div>
);
};// Toggling boolean values cleanly
const LightSwitch = () => {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(prev => !prev)}>
{isOn ? "ON" : "OFF"}
</button>
);
};// Correctly updating objects with the spread operator
const UserProfile = () => {
const [user, setUser] = useState({ name: 'Dev', age: 27 });
const birthday = () => {
// WRONG: user.age = user.age + 1; setUser(user); (No reference change)
// RIGHT: Spread details and overwrite target property
setUser((prevUser) => ({
...prevUser,
age: prevUser.age + 1
}));
};
return <button onClick={birthday}>Age: {user.age}</button>;
};// Correctly modifying arrays
const TodoList = () => {
const [todos, setTodos] = useState([]);
const addTodo = (text) => {
const newTodo = { id: Date.now(), text };
// Add item (creates new array)
setTodos((prevTodos) => [...prevTodos, newTodo]);
};
const removeTodo = (id) => {
// Remove item (creates filtered array)
setTodos((prevTodos) => prevTodos.filter(todo => todo.id !== id));
};
return <button onClick={() => addTodo("Learn State")}>Add Task</button>;
};🎯 Section 5 Interview Questions (10+)
1. What is state in React and how is it different from props?
State is local, mutable variable data managed internally by a component, used to track dynamic values between renders. Props are read-only configuration attributes passed by a parent to configure the child.
2. What does useState return?
useState returns an array containing exactly two items: (1) the current state value, and (2) an updater function that allows you to change the state and trigger a re-render.
3. Why are state updates asynchronous in React?
React batches multiple state updates together into a single render pass to optimize performance. If state updates were synchronous, updating three state variables consecutively would cause three expensive, redundant visual updates.
4. What is a functional update in useState and when should you use it?
A functional update is passing a callback function to the state updater (e.g., setState(prev => prev + 1)). You should use it whenever your new state depends on the previous state value to prevent bugs caused by async batching.
5. How do you update a nested object inside state without mutating it?
You must deep-copy nested levels using the spread operator or libraries like Immer (e.g., setState(prev => ({ ...prev, profile: { ...prev.profile, age: 30 } }))). Direct mutations will not change the outer reference, so React will not re-render.
6. Why is immutability important in React state?
Immutability allows React to perform cheap shadow reference equality checks (prev === next) to verify if data has changed. If state was mutated directly, comparing references would yield true, making state change detection computationally expensive.
7. What is derived state and why should you avoid storing it in state?
Derived state is data that can be calculated directly from existing props or state (e.g., item count from an array state). Storing it in a separate state creates synchronization bugs. It is best to compute derived values during the render process.
8. When should you use one state object vs multiple useState calls?
Use multiple useState calls when tracking independent variables (e.g., value and loading state). Use a single state object when variables are deeply related and updated together (e.g., username, password form states).
9. What is 'lifting state up' and when should you do it?
Lifting state up is moving state to a common parent component. You do it when two or more sibling components need to sync or share the same state data.
10. What happens when you call setState with the same value?
React performs an Object.is equality check. If the new state matches the current state, React bails out of rendering the component and its children, preventing redundant renders.
11. How does React batch state updates?
In React 18+, automatic batching consolidates all state updates triggered within event handlers, timeouts, promises, and native events into a single render cycle at the end of the microtask queue.
12. What is the difference between state and a ref for storing values?
Updating state triggers a component re-render, making it ideal for values rendered on the UI. Updating a Ref (useRef) mutates the .current property directly without triggering a re-render, making it ideal for persistent values not shown in the DOM (like timers).
Section 6: Hooks Deep Dive
Target Keyword: react hooks explained 2026
Hooks are functions that let you "hook into" React state and lifecycle features from functional components. By eliminating class components, hooks allow you to organize side effects and stateful logic into isolated, reusable functions.
Rules of Hooks
- Top-Level Calls Only: Do not call Hooks inside loops, conditions, or nested functions. This ensures React loads hooks in the same order on every render.
- React Functions Only: Call Hooks only from React functional components or custom Hooks.
Code Examples
// useEffect with Fetch and AbortController cleanup
import React, { useState, useEffect } from 'react';
const UserDetail = ({ userId }) => {
const [user, setUser] = useState(null);
useEffect(() => {
const controller = new AbortController();
const loadData = async () => {
try {
const res = await fetch(`https://api.example.com/users/${userId}`, {
signal: controller.signal
});
const data = await res.json();
setUser(data);
} catch (err) {
if (err.name !== 'AbortError') console.error(err);
}
};
loadData();
// Cleanup cancels pending requests when component updates/unmounts
return () => controller.abort();
}, [userId]);
return <div>{user ? user.name : "Loading..."}</div>;
};// useRef for DOM access and tracking previous state value
const AutoFocusInput = ({ value }) => {
const inputRef = React.useRef(null);
const prevValRef = React.useRef("");
React.useEffect(() => {
// Focus DOM input element on mount
inputRef.current?.focus();
}, []);
React.useEffect(() => {
// Keep track of previous state value
prevValRef.current = value;
}, [value]);
return (
<div>
<input ref={inputRef} type="text" value={value} />
<p>Previous Value: {prevValRef.current}</p>
</div>
);
};// useReducer for complex form states
const formReducer = (state, action) => {
switch (action.type) {
case 'FIELD_CHANGE':
return { ...state, [action.field]: action.value };
case 'RESET':
return { name: '', email: '' };
default:
return state;
}
};
const UserForm = () => {
const [state, dispatch] = React.useReducer(formReducer, { name: '', email: '' });
return (
<form>
<input
value={state.name}
onChange={(e) => dispatch({ type: 'FIELD_CHANGE', field: 'name', value: e.target.value })}
/>
<input
value={state.email}
onChange={(e) => dispatch({ type: 'FIELD_CHANGE', field: 'email', value: e.target.value })}
/>
</form>
);
};// useMemo and useCallback to stabilize references
const ExpensiveComponent = ({ list, onProcess }) => {
// Memoizes calculations to prevent recalculating on every render
const sortedList = React.useMemo(() => {
return [...list].sort((a, b) => b.score - a.score);
}, [list]);
// Memoizes function reference to prevent child re-renders
const handleItemClick = React.useCallback((id) => {
onProcess(id);
}, [onProcess]);
return (
<ul>
{sortedList.map(item => (
<li key={item.id} onClick={() => handleItemClick(item.id)}>
{item.name}
</li>
))}
</ul>
);
};🎯 Section 6 Interview Questions (10+)
1. What are React Hooks and why were they introduced?
Hooks are functions that let you use state and lifecycle methods in functional components. They were introduced in React 16.8 to share stateful logic without changing component hierarchies, avoid class component boilerplate, and prevent 'wrapper hell' caused by render props and HOCs.
2. What are the two rules of hooks?
Rules: (1) Only call Hooks at the top level of your functional components (never in loops, conditions, or nested functions), and (2) Only call Hooks from React function components or custom Hooks.
3. Explain the useEffect dependency array - what does [], [dep], and no array do?
No array: The effect runs after *every* render. Empty array ([]): The effect runs once after the initial render (mount). Dependency array ([dep]): The effect runs after the initial render and again whenever any item inside the dependency array changes references between renders.
4. How do you clean up a useEffect? Why is cleanup important?
You clean up an effect by returning a function from your useEffect callback. React calls this cleanup function when the component unmounts or before re-running the effect due to a dependency change. Cleanup is critical to prevent memory leaks, cancel active API requests, or clear intervals.
5. What is the difference between useEffect and useLayoutEffect?
useEffect runs asynchronously *after* the browser paints the screen, making it ideal for standard async operations like fetches. useLayoutEffect runs synchronously *before* the browser paints the screen, right after DOM mutations. It is used to measure layouts or prevent UI flickers before the screen updates.
6. When would you use useReducer over useState?
Use useReducer when a component has complex state logic involving multiple sub-values, when the next state depends on the previous state, or when actions trigger updates across multiple variables. It encapsulates state transformations cleanly into a reducer function.
7. What is the difference between useMemo and useCallback?
useMemo caches (memoizes) the *result* of a function calculation. useCallback caches the *function reference* itself. useMemo is for expensive calculations; useCallback is for preserving functional identities passed as props to memoized children.
8. How does useRef differ from state? What are its two main use cases?
Mutating a Ref's .current property does not trigger a component re-render, whereas modifying state does. Ref's two main use cases are: (1) accessing DOM nodes directly, and (2) storing mutable values that persist across renders without causing layout updates.
9. What is useContext and when should you use it vs prop drilling?
useContext consumes values directly from a React Context Provider without passing props down. Use it for global configurations like themes, authentication contexts, or internationalization parameters, but avoid it for high-frequency state updates due to re-render overhead.
10. What is the useTransition hook and what problem does it solve?
useTransition is a concurrent Hook that lets you mark state updates as non-urgent transitions. It prevents heavy UI calculations from blocking user interactions (like typing in an input field) by running the update in the background.
11. What is the new use() hook in React 19?
The use() hook in React 19 resolves promises and consumes Context inline. Unlike standard Hooks, use() can be called conditionally inside loops or if blocks, bringing native support for asynchronous control flow.
12. How does the React Compiler reduce the need for useMemo and useCallback?
The compiler automatically checks component structures and wraps values/methods in memoization during build time. This means developers no longer have to manually manage dependencies or write useMemo/useCallback declarations.
13. Can you call hooks inside conditions? What happens if you do?
No, calling hooks inside conditions violates the Rules of Hooks. React identifies hooks by their call order. Changing the sequence or number of hooks called between renders breaks React's internal array index mapping, causing state bugs.
14. What is useId and why is it useful for accessibility?
useId generates unique, stable ID strings that persist between client renders and server-side renders. It is used to bind HTML input elements to labels or ARIA descriptions, avoiding ID clashes in micro-frontend environments.
Section 7: Event Handling
Target Keyword: react event handling
Handling events in React is very similar to handling events on DOM elements, with some key syntactic differences: (1) React events are named using camelCase rather than lowercase, and (2) in JSX, you pass a function reference as the event handler rather than a string.
Synthetic Events
React wraps native browser events in a SyntheticEvent instance. This wrapper provides cross-browser compatibility by standardizing event behaviors across different rendering engines, while matching the W3C spec.
Code Examples
// Standard Event Handlers and parameters
const ButtonGroup = () => {
const handleClick = (e) => {
console.log("Button clicked!", e.target);
};
const handleCustomClick = (id, e) => {
console.log("Item ID clicked:", id, "Event:", e);
};
return (
<div className="flex gap-4">
{/* Simple reference */}
<button onClick={handleClick}>Click Me</button>
{/* Passing arguments via inline arrow function */}
<button onClick={(e) => handleCustomClick(101, e)}>Click 101</button>
</div>
);
};// Preventing default behaviors in event handlers
const SearchForm = () => {
const [query, setQuery] = React.useState("");
const handleSubmit = (e) => {
e.preventDefault(); // Prevents page reload
console.log("Submitting query:", query);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
</form>
);
};🎯 Section 7 Interview Questions (10+)
1. What are synthetic events in React?
Synthetic events are cross-browser wrappers around the browser's native events. They have the same interface as native events, including stopPropagation() and preventDefault(), but work identically across all platforms.
2. How do you pass arguments to an event handler in JSX?
You can pass arguments by wrapping the handler in an anonymous arrow function, e.g., onClick={(e) => handleClick(id, e)}, or by using function binding, e.g., onClick={handleClick.bind(this, id)}.
3. What is e.preventDefault() and when would you use it in React?
e.preventDefault() is used to stop default browser actions associated with an event. The most common use case is in form onSubmit handlers to prevent the browser from reloading the page during submission.
4. What is the difference between onClick={handleClick} and onClick={() => handleClick()}?
onClick={handleClick} passes the function reference directly, so it is only executed when the click occurs. onClick={() => handleClick()} creates a new anonymous arrow function on every render cycle which then calls handleClick. While visually similar, inline arrow functions can cause performance overhead in rendering loops of critical child components.
5. How does React's event delegation work under the hood?
React does not attach event listeners to individual DOM nodes. Instead, it delegates event listeners to the root element (e.g., #root) in React 17+. When an event bubbles up to the root, React maps it to the appropriate virtual element's handler.
6. What is e.stopPropagation() and when would you use it?
e.stopPropagation() stops an event from bubbling up the DOM tree, preventing parent event handlers from catching the event.
7. How do you handle keyboard events in React?
By attaching handlers like onKeyDown, onKeyUp, or onKeyPress and querying e.key or e.code to determine which key was pressed (e.g., e.key === 'Enter').
8. What is the difference between onChange in React vs HTML?
In native HTML, change triggers when the element loses focus. In React, onChange triggers immediately on every keystroke, behaving like the native 'input' event.
9. Why can't you return false to prevent default in React events?
Unlike standard HTML event attributes where returning false stops default actions, React requires you to call e.preventDefault() explicitly.
10. How do you handle events in class components vs functional components?
In class components, you bind event handler methods inside the constructor or declare them as arrow properties to preserve 'this'. In functional components, closures preserve lexical variables, eliminating 'this' context bindings.
11. What is event bubbling and how does React handle it?
Event bubbling is the progression of an event from target node up through parent nodes. React handles this using standard capturing and bubbling phases, naming bubbling events like onClick and capture events like onClickCapture.
Section 8: Conditional Rendering
Target Keyword: react conditional rendering
Conditional rendering in React refers to the practice of showing different parts of the UI depending on state or prop conditions. Because JSX is synthesized into plain JavaScript expressions, standard syntax like if statements, ternaries, and logical operators are fully operational.
Code Examples
// Common conditional rendering patterns
const LoadingSpinner = () => <div>Loading...</div>;
const ErrorMessage = ({ error }) => <div>Error: {error}</div>;
const UserPanel = ({ isLoading, error, data }) => {
// Pattern 1: Early return (ideal for top-level checks)
if (isLoading) return <LoadingSpinner />;
if (error) return <ErrorMessage error={error} />;
if (!data) return null; // Render nothing
return (
<div className="profile">
<h2>{data.name}</h2>
{/* Pattern 2: Ternary operator inside JSX */}
{data.isPremium ? (
<span className="badge-gold">Premium Member</span>
) : (
<span className="badge-free">Free Account</span>
)}
{/* Pattern 3: Short-circuit logical AND (&&) */}
{data.hasNotifications && <span className="dot">●</span>}
</div>
);
};🎯 Section 8 Interview Questions (10+)
1. What are the different ways to conditionally render in React?
Ways: (1) if/else statements (valid outside JSX), (2) ternary operators (condition ? expr1 : expr2), (3) logical AND operator (condition && JSX), (4) early return from the component, and (5) switch/case blocks mapped to helper methods.
2. What is the danger of using && with falsy values like 0?
If the left-hand operand evaluates to 0, JavaScript treats it as falsy and returns the number 0 instead of executing the right-hand operand. React renders numbers directly, meaning the text '0' will be output onto the screen. To prevent this, convert the condition to a boolean explicitly, e.g., array.length > 0 && <List />.
3. When would you return null from a component?
You return null when you want to explicitly hide a component from rendering (e.g., hiding a dialog modal or loading overlay when its display flag is false) without affecting other DOM nodes.
4. What is the ternary operator pattern for conditional rendering?
It is used within JSX to select between two different elements based on a boolean parameter. Example: {isLoggedIn ? <LogoutButton /> : <LoginButton />}.
5. How do you render different components based on user role?
You can map roles to components inside a configuration object or use switch-case statements, returning the correct markup matching the user's role.
6. How is conditional rendering in React different from v-if in Vue?
Vue's v-if is a template directive that compiles down to rendering code. React has no special template directives-it relies on standard JavaScript syntax (ternaries, logic operators, early returns) because JSX compiles directly to normal JS function calls.
7. What is the 'early return' pattern and why is it cleaner?
Early return is writing condition checks at the top of a component function that return JSX immediately (e.g., if (loading) return <Loader />). This prevents deep nesting of nested ternaries inside the main return statement, making the code much easier to read.
8. How do you handle loading, error, and success states in one component?
By checking status values in order (often using early returns) to return the specific views for each status (Loading, Error, and then final Data Layout).
9. Can you use a switch statement inside JSX? What's the alternative?
You cannot write a switch block directly inside JSX brackets because JSX only accepts JavaScript expressions, not statement blocks. The alternative is to execute the switch inside a helper function or IIFE (Immediately Invoked Function Expression) and call it inside JSX.
10. How do you conditionally apply CSS classes in React?
Using template literals (e.g., className={`box ${active ? 'active' : ''}`}) or library utilities like 'clsx' or 'classnames' for clean class merges.
Section 9: Lists and Keys
Target Keyword: react lists and keys
Rendering lists of data is a core task in modern applications. React uses standard JavaScript array map methods to iterate over arrays and return elements. However, each child element in a list must be given a unique, stable key prop to help React identify adjustments.
Code Examples
// Standard list rendering with key and removal actions
const ContactList = () => {
const [contacts, setContacts] = React.useState([
{ id: 'uid-1', name: 'John Doe', email: '[email protected]' },
{ id: 'uid-2', name: 'Jane Smith', email: '[email protected]' }
]);
const deleteContact = (id) => {
// Filter array (creates new reference)
setContacts(contacts.filter(c => c.id !== id));
};
return (
<ul className="divide-y">
{contacts.map((contact) => (
// KEY is attached to root tag returned by map loop
<li key={contact.id} className="py-2 flex justify-between">
<span>{contact.name} ({contact.email})</span>
<button onClick={() => deleteContact(contact.id)}>Delete</button>
</li>
))}
</ul>
);
};🎯 Section 9 Interview Questions (10+)
1. Why does React require a key prop on list items?
React requires a key prop during reconciliation to map virtual elements to DOM nodes. Stable keys allow React to recognize when items are added, deleted, or reordered, avoiding redundant DOM repaints.
2. What is wrong with using array index as a key?
If list items can be reordered, sorted, or removed, using index as a key leads to rendering bugs. React identifies state by key; if keys change index values, local state values (like active inputs) get bound to the wrong UI item.
3. What makes a good key value?
A good key is a unique, stable string identifier that does not change between render passes. Database IDs (UUIDs, auto-incrementing index values from databases) are ideal.
4. Does the key prop get passed to child components?
No. The key is reserved internally by React and is not passed to the child component as a prop. If a child component needs the key's value, you must pass it explicitly under a different prop name.
5. What happens when keys change between renders?
If a key changes, React completely destroys the corresponding DOM node, resets its local state, and recreates a new DOM node. This can be used intentionally to reset form states.
6. How would you render a list and handle removing an item from it?
Map over the array and assign the unique ID as the key. Pass the ID to a removal callback that updates the state array using .filter().
7. How do you render a nested/hierarchical list in React?
By nesting .map() loops. Ensure the outer loop maps outer items with a unique outer key, and the inner loop maps inner items with a unique inner key.
8. What is the difference between map() and forEach() for rendering?
map() returns a new array containing JSX elements, which React can render. forEach() returns undefined, which renders nothing in React.
9. How do you handle an empty list gracefully in React?
Use a ternary check on list length (e.g., list.length === 0 ? <EmptyState /> : list.map(...)) to display placeholder text when the collection is empty.
10. How would you implement pagination over a large list?
By keeping track of a 'currentPage' state and using array slice methods (e.g., list.slice(start, end)) to only render the subset of items for the active page.
Section 10: Forms in React
Target Keyword: react forms controlled uncontrolled
Form handling in React highlights the split between the DOM's native state management and React's component state. React handles this through two different paradigms: Controlled components and Uncontrolled components.
Code Examples
// Standard Controlled inputs using a unified handler
const RegisterForm = () => {
const [formData, setFormData] = React.useState({
username: "",
email: "",
subscribed: false
});
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setFormData((prev) => ({
...prev,
[name]: type === "checkbox" ? checked : value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submit:", formData);
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<input name="username" value={formData.username} onChange={handleChange} />
<input name="email" value={formData.email} onChange={handleChange} />
<input type="checkbox" name="subscribed" checked={formData.subscribed} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
};// Uncontrolled input utilizing useRef
const QuickContact = () => {
const emailRef = React.useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
// Read input directly from the DOM reference
alert("Email submitted: " + emailRef.current?.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" ref={emailRef} defaultValue="[email protected]" />
<button type="submit">Send</button>
</form>
);
};🎯 Section 10 Interview Questions (10+)
1. What is a controlled component in React?
A controlled component is an input element whose value is determined and updated by React state. Changes are handled via a callback function (like onChange) which updates the state variable.
2. What is an uncontrolled component and when would you use one?
An uncontrolled component is an input element whose value is managed directly by the DOM. You query it using Refs. They are useful for legacy integrations, simple non-validated fields, or file inputs where browser security forbids programmatic state control.
3. What is the difference between value and defaultValue on an input?
value binds an input directly to state, locking its value (controlled). defaultValue only configures the initial value when the element mounts, allowing the user to type freely without state bindings (uncontrolled).
4. How do you handle multiple form inputs with a single state object?
By setting the 'name' attribute on each input to match properties in a state object, and writing a generic handler: setState(prev => ({ ...prev, [e.target.name]: e.target.value })).
5. How do you prevent default form submission in React?
Call e.preventDefault() in the onSubmit handler. This stops browser page refreshes, letting React process validation and API calls.
6. How do you reset a form in React?
For controlled forms, reset the state object back to its initial properties. For uncontrolled forms, invoke formRef.current.reset() directly.
7. What are the React equivalents for select, textarea, and checkbox?
select takes a value prop matching selected option values. textarea takes value as a standard attribute rather than HTML innerText children. checkbox takes a checked boolean prop instead of value.
8. How would you implement form validation without a library?
By maintaining an 'errors' state object. Validate fields in handleSubmit or onChange, populate the errors object with error strings, and render warning messages if errors exist.
9. Why is React Hook Form preferred over manual form state in production?
React Hook Form manages form states in uncontrolled references, drastically reducing re-renders on every keystroke. It provides fast validation, small bundles, and clean syntax.
10. What is the ref prop used for in forms?
The ref prop provides access to raw HTML DOM nodes. It's used to trigger element focus, scroll inputs into view, or read values in uncontrolled forms.
11. How do you handle file inputs in React?
File inputs are always uncontrolled. Keep state references to files using onChange, reading the file list from e.target.files[0] and attaching it to a FormData object for uploads.
Section 11: Context API
Target Keyword: react context api tutorial 2026
The React Context API solves the prop drilling problem by providing a way to share values globally down a component tree without manually threading props through intermediate layout layers.
Code Examples
// Full Context Setup: Creation, Provider, and Custom Hook
import React, { createContext, useContext, useState } from 'react';
// 1. Create Context
const ThemeContext = createContext(undefined);
// 2. Create Custom Provider
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("dark");
const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
// 3. Create Custom Hook to consume context safely
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};🎯 Section 11 Interview Questions (10+)
1. What is the Context API and what problem does it solve?
The Context API allows sharing data globally down a component tree without prop drilling. It solves the issue of threading variables (like theme, locale, user session) through multiple middle components that have no interest in the values.
2. What are the three parts of the Context API?
Parts: (1) React.createContext() to define the context, (2) Context.Provider to wrap parent hierarchies and declare values, and (3) React.useContext() to read context values in child components.
3. How do you provide and consume context?
Provide context by wrapping components in <Context.Provider value={value}>. Consume it inside functional components by executing const contextVal = useContext(Context).
4. What is the performance problem with Context and how do you mitigate it?
Whenever the Provider's value reference updates, all components consuming that context are forced to re-render. To mitigate this, split context into separate providers (e.g., StateProvider and DispatchProvider), wrap child elements in React.memo, or compute state using state libraries.
5. Can you have multiple contexts in one app?
Yes. You can nest multiple context providers at the root or at feature-level boundaries to separate concerns (e.g., ThemeProvider inside AuthProvider).
6. What is the difference between Context API and Redux?
Context is a dependency injection tool built into React. Redux is an external state management library that provides developer tools, middleware, actions, and reducers. Redux is optimized for high-frequency updates; Context causes cascading re-renders when data shifts.
7. When should you use Context API vs a state management library?
Use Context for static or slow-changing global data (theme, auth, lang). Use state management libraries (Zustand, Redux) for frequent, complex, or performance-critical state updates (e.g., gaming engines, multi-column forms).
8. What happens when a Context value changes? Which components re-render?
Every component that imports useContext() referencing that specific context will re-render, regardless of whether they consume the specific field that changed inside the context value.
9. How do you create a custom hook that wraps a context?
Define a hook that calls useContext(MyContext), checks if the return is undefined (indicating consumer is placed outside provider bounds), and throws a clear error if so.
10. What is the default value of a context and when is it used?
The default value is passed when calling createContext(defaultValue). It is only used if a component consumes context without being wrapped inside a matching Provider in its parent hierarchy.
11. How do you split context to avoid unnecessary re-renders?
By storing state in one context (e.g., stateContext) and dispatch functions in another (e.g., dispatchContext). This prevents state changes from causing re-renders in components that only trigger actions.
Section 12: State Management Libraries
Target Keyword: react state management 2026 zustand redux
For larger apps, native React state can become complex. In 2026, global state is divided into: Server state (handled by TanStack Query) and Client state (Zustand for lightweight needs, Redux Toolkit for complex enterprise setups).
Code Examples
// Creating a lightweight Zustand Store
import { create } from 'zustand';
export const useCartStore = create((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
clearCart: () => set({ items: [] })
}));
// Usage in Component:
// const items = useCartStore((state) => state.items);
// const addItem = useCartStore((state) => state.addItem);// Standard Redux Toolkit Slice
import { createSlice } from '@reduxjs/toolkit';
const authSlice = createSlice({
name: 'auth',
initialState: { user: null, loading: false },
reducers: {
setUser: (state, action) => {
// Immer handles mutability safety under the hood
state.user = action.payload;
},
logout: (state) => {
state.user = null;
}
}
});
export const { setUser, logout } = authSlice.actions;
export default authSlice.reducer;🎯 Section 12 Interview Questions (10+)
1. What is the difference between local state, server state, and global state?
Local state: state scoped to a single component (useState). Server state: cached data fetched from APIs (useQuery). Global state: state shared across multiple pages or unrelated layout components (Zustand, Redux).
2. What is Redux and what is the Redux data flow?
Redux is a predictable state container. Unidirectional data flow: Components trigger Actions -> Dispatch relays actions to Reducers -> Reducers update the Store state -> Store notifies subscribing components to re-render.
3. What is Redux Toolkit and how does it simplify Redux?
Redux Toolkit (RTK) is the official opinionated toolset for Redux. It removes boilerplate by generating action creators automatically, configuring standard store setups, and integrating Immer to allow 'mutable' assignment syntax in reducers.
4. What are slices in Redux Toolkit?
A Slice is a collection of Redux reducer logic and actions bundled together for a specific domain module (e.g., auth, cart).
5. What is Zustand and how does it differ from Redux?
Zustand is a lightweight state manager that uses closures and hook structures. It requires no Providers, has minimal boilerplate, and operates via simple state actions without complex action/reducer pipelines.
6. Why is Zustand preferred over Redux for smaller apps in 2026?
Zustand sets up in under 5 lines of code, adds minimal bundle weight (~1KB), doesn't require nesting components in Providers, and allows selector-based subscription optimization.
7. What is TanStack Query and what problem does it solve?
TanStack Query is a server-state library. It manages remote data caching, syncs local states with backends, handles loading/error statuses, and provides stale-while-revalidate utilities.
8. What is the difference between useQuery and useMutation?
useQuery is used for fetching/GET requests (read data). useMutation is used for creating/updating/deleting/POST/PUT/DELETE requests (write/mutate data).
9. What is stale-while-revalidate and why is it powerful for UX?
It returns cached stale data immediately to make the UI feel instant, while simultaneously refetching fresh data in the background to update the cache and screen.
10. When should you use Context API vs Zustand vs Redux?
Context: slow-changing global variables. Zustand: medium-to-large apps needing clean global states. Redux: massive enterprises with elaborate state pipelines and debugging logs.
11. What is the single source of truth principle?
A state architecture design where every piece of data is owned by only one place, ensuring different parts of the application do not hold out-of-sync copies.
12. How does React Query's caching work?
It caches API responses under specific query keys. If a query is rendered within cache limits, React Query serves it from cache while resolving background revalidation based on configuration.
Section 13: React Router
Target Keyword: react router v6 tutorial 2026
Routing in Single Page Applications (SPAs) intercept browser navigation to dynamically update parts of the layout, preventing full page reloads and providing instant navigations.
Code Examples
// React Router v6 setup with layouts and dynamic routes
import { BrowserRouter, Routes, Route, Link, Outlet, useParams } from 'react-router-dom';
const AppLayout = () => (
<div>
<nav className="flex gap-4 p-4 border-b">
<Link to="/">Home</Link>
<Link to="/products">Products</Link>
</nav>
<main className="p-6">
{/* Outlet renders matched child route components */}
<Outlet />
</main>
</div>
);
const ProductDetail = () => {
const { productId } = useParams(); // Reading dynamic slug
return <h2>Showing Product: {productId}</h2>;
};
const RootRouter = () => (
<BrowserRouter>
<Routes>
<Route path="/" element={<AppLayout />}>
<Route index element={<h1>Home Page</h1>} />
<Route path="products/:productId" element={<ProductDetail />} />
</Route>
</Routes>
</BrowserRouter>
);🎯 Section 13 Interview Questions (10+)
1. What is client-side routing and how does it implement it?
Client-side routing changes the active viewport content without sending an HTTP document request back to the server. It uses the History API to sync URLs with local application state.
2. What are the main components of React Router v6?
Components: BrowserRouter (context provider), Routes (parent switch block), Route (maps path to element), Link/NavLink (navigation buttons), and Outlet (layout placeholder).
3. What is the difference between Link and a in React?
a tags perform a full browser page refresh. Link intercepts navigation, updating the history stack and DOM rendering inline while keeping application state intact.
4. How do you access URL parameters in React Router v6?
Use the useParams() hook, which returns a key-value object of dynamic URL tokens defined in Route paths (e.g., :productId).
5. What is useNavigate and how does it differ from Redirect?
useNavigate() is a hook returning a function that lets you navigate programmatically in JavaScript. Redirect was a component used in v5 to declare redirections; v6 replaces it with <Navigate to='...' />.
6. How do you implement a protected route?
Create a wrapper component that checks user credentials. If authentication passes, render the child Outlet; otherwise, redirect using <Navigate to='/login' replace />.
7. What is useLocation and what information does it provide?
useLocation() returns an object representing the current URL path location, including pathname, search (query params), hash, and navigation state.
8. What is the difference between BrowserRouter and HashRouter?
BrowserRouter uses standard paths (e.g., /dashboard) and requires server rewrite support. HashRouter appends hashes (e.g., #/dashboard) and doesn't require server rewrites because the hash is never sent to the server.
9. How do you implement nested routes in React Router v6?
By nesting Route tags inside Route tags, and rendering the <Outlet /> component inside the parent Route element to specify where the child components should render.
10. How do you handle 404 pages in React Router?
By placing a catch-all route at the bottom of the Routes list: <Route path='*' element={<NotFound />} />.
11. How do you pass state via navigation in React Router?
Pass state objects inside the navigate function options: navigate('/path', { state: { from: 'dashboard' } }). Retrieve it on the destination page using useLocation().state.
12. What is lazy loading of routes and how do you implement it?
Lazy loading splits route bundles so code is only requested when users navigate to that route. Implement it using React.lazy() with React Suspense fallback components wrapping Route elements.
Section 14: Performance Optimization
Target Keyword: react performance optimization 2026
Optimizing React applications involves preventing redundant updates, reducing bundle sizes, and compiling components using build-time optimization structures.
Code Examples
// Using React.memo to prevent re-renders when parent states change
import React, { useState } from 'react';
const ExpensiveDisplay = React.memo(({ title }) => {
console.log("Expensive rendered!");
return <h3>Display: {title}</h3>;
});
const Parent = () => {
const [text, setText] = useState("");
const [count, setCount] = useState(0);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setCount(c => c + 1)}>Clicks: {count}</button>
{/* ExpensiveDisplay will NOT re-render when text changes because text is not a prop here */}
<ExpensiveDisplay title="Stable Dashboard" />
</div>
);
};🎯 Section 14 Interview Questions (10+)
1. What triggers a re-render in React?
A component re-renders if its local state changes, if a parent component forces a re-render, if props change references, or if a context value it consumes updates.
2. What is React.memo and how does it prevent re-renders?
React.memo is a higher-order component. It performs a shallow comparison of incoming props; if props haven't changed reference, it skips rendering the component, reusing the last rendered result.
3. What is the difference between useMemo and React.memo?
React.memo is a Higher-Order Component wrapping entire child elements. useMemo is a React Hook used inside components to memoize heavy calculations.
4. When should you NOT use useMemo or useCallback?
Do not use them for simple, cheap operations. The compiler dependency-checking and caching logic has performance overhead, which can exceed the execution cost of a simple function.
5. What is code splitting and how do React.lazy and Suspense enable it?
Code splitting splits bundling files into smaller modular scripts. React.lazy dynamically imports components while <Suspense> renders fallback placeholders (loaders) while the scripts resolve.
6. What is list virtualization and when do you need it?
List virtualization only renders items currently visible in the user's viewport. You need it when rendering thousands of items to avoid slowing down DOM structures.
7. What is the React Profiler and how do you use it to find performance issues?
A tool in DevTools that collects data on when components render, how long they take, and why they scheduled the update, pointing out bottlenecks.
8. What is referential equality and why does it matter for React performance?
JavaScript objects/arrays/functions compare by reference pointer, not values. Passing inline objects or functions down as props causes children to assume props changed reference, triggering redundant renders.
9. How does the React Compiler in 2026 change memoization strategy?
It automates optimization. Developers no longer need to write useMemo or useCallback, as the compiler does it automatically at compile-time.
10. What is the key prop's role in performance during list updates?
It tells React which DOM nodes can be reused or moved during list operations, preventing nodes from being completely destroyed and rebuilt.
11. What is tree shaking and how does it reduce bundle size?
A build optimization process (like in Vite/Rollup) that analyzes import chains and strips unused code from the final bundle scripts.
12. How do you measure and improve Core Web Vitals in a React app?
Track metrics (LCP, FID, CLS) using Lighthouse. Improve them via image optimizations, lazy loading, script splitting, CDN distribution, and layout stability.
Section 15: Custom Hooks
Target Keyword: react custom hooks examples
Custom Hooks allow you to extract component state and lifecycle logic into reusable JavaScript functions, keeping components focused strictly on rendering UI.
Code Examples
// Custom Hook to manage local storage state
import { useState, useEffect } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}// Custom Hook to debounce high-frequency state updates (like inputs)
import { useState, useEffect } from 'react';
export function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler); // Cleanup on update
}, [value, delay]);
return debouncedValue;
}🎯 Section 15 Interview Questions (10+)
1. What is a custom hook in React?
A custom hook is an arbitrary JavaScript function whose name starts with 'use', which can call other React hooks, abstracting complex component logic into a reusable block.
2. What naming convention must custom hooks follow and why?
They must start with the prefix 'use'. This tells React's build tools and compiler that the function contains hook calls, enabling rules-of-hooks validations.
3. How do custom hooks differ from regular utility functions?
Utility functions can perform calculations but cannot invoke state or lifecycle hooks. Custom hooks can execute other hooks (useState, useEffect) and manage component lifecycles.
4. Can custom hooks use other hooks? Can they use other custom hooks?
Yes. Custom hooks can use core React hooks and call other custom hooks, creating nested logic abstractions.
5. How would you build a useFetch hook?
Set up loading, error, and data state variables. Inside a useEffect, run an async fetch function that handles loading status, stores the response in state, and handles errors.
6. How do you test a custom hook?
Using the renderHook() utility from React Testing Library. It wraps hook executions inside mock components, letting you inspect return values.
7. What is the benefit of custom hooks over HOCs or render props?
Custom hooks do not add extra components to the DOM hierarchy, which avoids 'wrapper hell', simplifies unit tests, and allows for cleaner syntax.
8. How would you build a useDebounce hook?
Maintain a debouncedState variable. Set up a useEffect that starts a setTimeout delay to update the debouncedState, and returns a cleanup callback that executes clearTimeout.
9. Can two components share state through a custom hook?
No. Custom hooks share stateful *logic*, not state itself. Each component calling the hook initializes its own local state instance.
10. What is the difference between sharing logic and sharing state in custom hooks?
Sharing logic means reusing state lifecycles (each component gets its own values). Sharing state means components read from the exact same data source (like Context or global stores).
11. How would you build a useLocalStorage hook?
Initialize useState with a lazy function that reads a key from localStorage. Write a useEffect that sets item values in localStorage whenever the key or value updates.
Section 16: React with TypeScript
Target Keyword: react typescript tutorial 2026
TypeScript provides static type analysis, which prevents runtime bugs and enhances IDE autocompletions in large React codebases.
Code Examples
// Typing Props and Event handlers in React + TypeScript
import React, { useState } from 'react';
interface ButtonProps {
label: string;
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
variant?: 'primary' | 'secondary';
}
const PrimaryButton: React.FC<ButtonProps> = ({ label, onClick, variant = 'primary' }) => {
return <button onClick={onClick} className={`btn btn-${variant}`}>{label}</button>;
};
const InputForm = () => {
const [val, setVal] = useState<string>(""); // Generics on useState
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setVal(e.target.value);
};
return <input type="text" value={val} onChange={handleChange} />;
};🎯 Section 16 Interview Questions (10+)
1. What are the benefits of using TypeScript with React?
Static type-checking catches type mismatches before runtime. It offers rich IDE autocomplete, improves refactoring speed, and serves as self-documenting code.
2. How do you type props in a React component?
By defining an interface or type alias mapping keys to types, and typing the props argument, e.g., const MyComponent = ({ label }: MyProps) => ...
3. What is the difference between interface and type for props?
Interfaces support declaration merging and are optimized for extension. Types can declare unions (|), intersections (&), and primitive mappings, which are useful for complex props.
4. How do you type useState when the initial value is null?
Pass a union parameter into the useState generic: const [user, setUser] = useState<User | null>(null).
5. How do you type an onChange event on an input?
Use React.ChangeEvent<HTMLInputElement> for input tags, or React.FormEvent for general forms.
6. What is React.FC and why do some developers avoid it?
React.FC stands for FunctionComponent. Some developers avoid it because it historically included implicit children properties, which was solved in React 18.
7. How do you type the children prop?
Explicitly declare it inside the props interface as React.ReactNode (which supports text, elements, fragments, or arrays).
8. What is React.ReactNode vs React.ReactElement?
React.ReactElement represents a single JSX node object returned by createElement. React.ReactNode represents any renderable item: elements, fragments, strings, numbers, or arrays.
9. How do you type a generic reusable component?
Declare a generic type variable in the component definition: const List = <T,>({ items }: { items: T[] }) => ...
10. How do you type useRef when using it for a DOM element?
Initialize it with the DOM node type and null: const inputRef = useRef<HTMLInputElement>(null).
11. What is ComponentProps<typeof Component> useful for?
It extracts the prop types from an existing React component, letting you reuse them without needing to export the original interface.
Section 17: React 19 - New Features
Target Keyword: react 19 new features 2026
React 19 marks a major shift towards compiler-driven optimizations and async UI transitions, making modern applications faster and reducing developer boilerplate.
Code Examples
// React 19 use() Hook resolving promises inline
import React, { use, Suspense } from 'react';
const fetchMessage = () => fetch('/api/msg').then(res => res.json());
const msgPromise = fetchMessage(); // Define outside or memoize
const MessagePanel = () => {
// use() resolves the promise during rendering
const message = use(msgPromise);
return <p>Fetched Message: {message.text}</p>;
};
const App = () => (
<Suspense fallback={<div>Loading promise...</div>}>
<MessagePanel />
</Suspense>
);// useOptimistic Hook for instant UI updates
import { useOptimistic, useState } from 'react';
const TaskPanel = () => {
const [tasks, setTasks] = useState([{ id: 1, text: "Learn React" }]);
const [optimisticTasks, setOptimisticTasks] = useOptimistic(
tasks,
(state, newTaskText) => [...state, { id: Date.now(), text: newTaskText, sending: true }]
);
const addTask = async (formData) => {
const text = formData.get("taskText");
setOptimisticTasks(text); // Trigger instant optimistic view
// Perform real network request
await fetch('/api/tasks', { method: 'POST', body: JSON.stringify({ text }) });
setTasks(prev => [...prev, { id: Date.now(), text }]);
};
return (
<form action={addTask}>
<input name="taskText" required />
<button type="submit">Add Task</button>
<ul>
{optimisticTasks.map(t => (
<li key={t.id}>{t.text} {t.sending && "(Sending...)"}</li>
))}
</ul>
</form>
);
};🎯 Section 17 Interview Questions (10+)
1. What is the React Compiler and what does it automate?
The React Compiler is a build-time tool that auto-memoizes component values and functional references, removing the need for manual useMemo and useCallback hooks.
2. What are React Server Components and how do they differ from regular components?
Server Components render exclusively on the server, sending pre-rendered structures to the client. This reduces client bundle sizes since client code doesn't need data fetching dependencies.
3. What is the use() hook and what can it consume?
The use() hook is a React 19 hook that can consume Promises and Context inline. Unlike standard hooks, it can be called inside conditions and loops.
4. What are React Actions in React 19?
Actions are asynchronous transitions. When you pass an async function to HTML elements (like <form action={handler}>), React automatically handles pending states, error boundaries, and optimistic updates.
5. What is useOptimistic and when would you use it?
useOptimistic is a hook that temporarily renders expected data while an async operation completes. It's used to make UI updates feel instant, reverting to server state if the request fails.
6. What is useFormStatus and what problem does it solve?
useFormStatus is a hook that accesses submission details of parent forms without prop drilling. It returns properties like 'pending' and 'data'.
7. How has ref handling changed in React 19?
React 19 supports passing 'ref' as a standard prop to functional components. This deprecates the React.forwardRef() wrapper.
8. What is the difference between Server Components and SSR?
SSR (Server-Side Rendering) converts HTML on servers to return complete static structures. Server Components are rendering units that never re-render on clients; they yield interactive JSON structures, not plain HTML, and can coexist with client components.
9. What is a Server Action?
A Server Action is a client-callable function that executes on the server. You declare it using the 'use server' directive at the top of the function block.
10. How does React 19 handle document metadata (<title>, <meta>)?
React 19 natively supports rendering metadata tags (title, meta, link) directly inside components. It automatically hoists them to the HTML document head, removing the need for libraries like React Helmet.
11. What is useDeferredValue and how does it help with performance?
It defers updating heavy parts of the UI while keeping the text inputs responsive, rendering background components with stale values until tasks complete.
Section 18: Testing React Components
Target Keyword: react testing tutorial jest 2026
Testing verifies that UI components match expected behaviors when interacting with users, without breaking features during updates.
Code Examples
// Standard Vitest/RTL component test
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test, vi } from 'vitest';
import ClickButton from './ClickButton';
test('renders button and processes click event', async () => {
const handler = vi.fn();
render(<ClickButton onClick={handler} label="Submit" />);
const btn = screen.getByRole('button', { name: /submit/i });
expect(btn).toBeInTheDocument();
await userEvent.click(btn);
expect(handler).toHaveBeenCalledTimes(1);
});🎯 Section 18 Interview Questions (10+)
1. What is React Testing Library and what philosophy guides it?
React Testing Library (RTL) is a component testing utility. Its core philosophy is: 'The more your tests resemble the way your software is used, the more confidence they can give you.' It tests user behavior rather than internal implementation details.
2. What is the difference between getBy, findBy, and queryBy?
getBy: returns matching nodes synchronously, throwing an error if zero or multiple elements are found. queryBy: returns nodes synchronously, returning null if elements don't exist (useful for asserting element absence). findBy: returns a promise that resolves when elements appear in the DOM, useful for async elements.
3. How do you test asynchronous behavior in RTL?
Use async/await with findBy queries (e.g., const item = await screen.findByText('Loaded')), or wrap state checks inside waitfor().
4. What is the difference between fireEvent and userEvent?
fireEvent dispatches raw DOM events synchronously. userEvent simulates realistic browser interactions (e.g., userEvent.click triggers hover, focus, mouse down, and click events), making it more reliable.
5. What is Mock Service Worker (MSW) and why is it preferred for API mocking?
MSW intercepts requests at the network level using Service Workers. It lets you run tests without mocking window.fetch, keeping code clean and accurate.
6. What is snapshot testing and when should you avoid it?
Snapshot testing compares rendered component markups against stored baselines. Avoid it for active, changing layouts, as minor structural updates invalidate snapshots, causing test noise.
7. How do you test a component that uses useContext?
Wrap the test component in the matching Context.Provider inside render(), passing mock values in the provider value attribute.
8. How do you test a custom hook?
Use the renderHook() utility, which runs the hook inside a test component and returns a 'result' object containing hook returns.
9. What is the difference between unit, integration, and E2E tests for React?
Unit tests test single components or functions. Integration tests test how components communicate. E2E tests test the whole flow from client to server (using tools like Playwright).
10. What is Vitest and how does it compare to Jest for React projects?
Vitest is a Vite-native test runner. It is faster than Jest because it shares configurations directly with the Vite compiler, whereas Jest requires separate babel configurations.
11. How do you test error boundaries?
By rendering a child component that intentionally throws an error, and asserting that the fallback layout replaces the child components.
Section 19: React Patterns & Best Practices
Target Keyword: react design patterns 2026
Design patterns resolve common architectural challenges in React development, keeping components extensible and easy to test.
Code Examples
// Compound Component Pattern (like select/option)
import React, { createContext, useContext, useState } from 'react';
const TabsContext = createContext(undefined);
export const Tabs = ({ children, defaultIndex = 0 }) => {
const [activeIndex, setActiveIndex] = useState(defaultIndex);
return (
<TabsContext.Provider value={{ activeIndex, setActiveIndex }}>
<div className="tabs-container">{children}</div>
</TabsContext.Provider>
);
};
Tabs.Tab = ({ index, label }) => {
const { activeIndex, setActiveIndex } = useContext(TabsContext);
return (
<button
onClick={() => setActiveIndex(index)}
className={activeIndex === index ? 'active' : ''}
>
{label}
</button>
);
};
Tabs.Panel = ({ index, children }) => {
const { activeIndex } = useContext(TabsContext);
return activeIndex === index ? <div>{children}</div> : null;
};🎯 Section 19 Interview Questions (10+)
1. What is the compound component pattern?
A pattern where components work together to share state implicitly (e.g., <Tabs> and <Tabs.Tab>). It provides clean APIs without forcing prop drilling.
2. What are Higher-Order Components? What are their downsides?
An HOC is a function that takes a component and returns an upgraded component (e.g., withRouter(App)). Downsides: it adds noise to debugger trees, causes prop clashes, and is largely replaced by hooks.
3. What is the render props pattern? When would you still use it?
A pattern where components accept functions that return JSX as props, delegating rendering logic. You use it in legacy libraries, though hooks are now preferred.
4. What is an Error Boundary? Can you make one with hooks?
An Error Boundary is a class component that catches JavaScript errors in child trees. You cannot create one with functional components because hooks don't support getDerivedStateFromError or componentDidCatch.
5. What is a Portal and when do you need one?
A Portal renders elements outside their parent DOM hierarchy, mounting them to separate DOM nodes (e.g., document.body). They are used for modals, tooltips, and dropdown overlays.
6. What is Suspense and how does it work with lazy loading?
Suspense is a React feature that suspends rendering while resources load, displaying a fallback loader until client components resolve.
7. What is the presentational/container component pattern?
A pattern separating business logic from UI representation. Container components manage state and fetches; Presentational components receive props and render elements.
8. What is lazy initialization of state and when is it useful?
Passing a function to useState (e.g., useState(() => readDb())). It only executes during the component's initial mount, avoiding heavy calculations on re-renders.
9. What is composition over inheritance in React?
React's design recommendation. Instead of extending class components, build modules by nesting components and passing elements as props (composition).
10. How do you handle deeply nested context with multiple providers?
By creating a unified wrapper provider (e.g., AppProviders) that groups all context tags, avoiding nested tag indentations at the root level.
11. What is a compound component and what are its advantages over prop-heavy APIs?
It encapsulates state implicitly. Sibling components communicate via Context, giving developers control over layouts without needing long lists of parent parameters.
Section 20: React and APIs - Data Fetching
Target Keyword: react data fetching 2026
Connecting React components to remote REST or GraphQL APIs is a core requirement of modern applications. React provides hook paradigms to fetch and cache remote resources.
Code Examples
// Fetching data with TanStack Query (React Query)
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
const fetchTodos = () => fetch('/api/todos').then(res => res.json());
const addTodoApi = (newTodo) => fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo)
}).then(res => res.json());
const TaskList = () => {
const queryClient = useQueryClient();
// GET Query
const { data: todos, isLoading, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos
});
// POST Mutation
const mutation = useMutation({
mutationFn: addTodoApi,
onSuccess: () => {
// Invalidate cache and trigger refetch
queryClient.invalidateQueries({ queryKey: ['todos'] });
}
});
if (isLoading) return <span>Loading tasks...</span>;
if (error) return <span>Error loading tasks</span>;
return (
<div>
<button onClick={() => mutation.mutate({ text: 'New Task' })}>Add Task</button>
<ul>
{todos.map(t => <li key={t.id}>{t.text}</li>)}
</ul>
</div>
);
};🎯 Section 20 Interview Questions (10+)
1. How do you fetch data in React?
Using the fetch API or Axios inside useEffect, or by utilizing server state managers like TanStack Query or SWR.
2. What is a race condition in useEffect data fetching and how do you fix it?
A race condition occurs when multiple async requests resolve out of order. Fix it using an active boolean flag or an AbortController to cancel previous requests.
3. What is an AbortController and how is it used?
A browser utility that cancels active fetch requests. You associate it with a fetch via options and trigger controller.abort() inside the useEffect cleanup function.
4. What is TanStack Query and why is it preferred over manual useEffect fetching?
A state manager built for async data. It handles cache layers, eliminates request duplicates, manages loading/error flags, and manages retries automatically.
5. What is the difference between server state and client state?
Client state is local to browsers (toggles, input text). Server state belongs to databases and requires API requests to read or modify.
6. What is stale-while-revalidate and how does it improve UX?
An update pattern serving cached values immediately, while running background fetch checks to refresh the data when the call resolves.
7. What is useQuery and what does it return?
A hook that fetches data. It returns variables like data, isLoading, isError, status, and refetch functions.
8. What is useMutation and how do you invalidate queries after mutation?
A hook for API writes (POST/PUT). Invalidate caches using queryClient.invalidateQueries({ queryKey }) inside the mutation's onSuccess callback.
9. What is the difference between Axios and Fetch?
Axios auto-parses JSON, supports interceptors, and handles timeouts out of the box. Fetch requires double Promises (response.json()) and manual error parsing.
10. How do you implement pagination with TanStack Query?
Bind page parameters to query keys (e.g., ['todos', page]). Updating page state triggers queries for the new key, caching page subsets.
11. What is SWR and how does it compare to TanStack Query?
SWR is a lightweight caching library from Vercel. It is simpler than TanStack Query, offering basic caching hooks but fewer mutations and cache-management features.
Section 21: React Project Architecture
Target Keyword: react project structure best practices 2026
Structuring massive codebase files requires a predictable layout system that isolates domains, manages dependency rules, and keeps code clean.
Code Examples
src/
features/ # Domain-driven features
auth/
components/ # Auth-specific widgets
hooks/ # Auth logic
api/ # Auth service/fetches
types/ # Auth types
dashboard/
shared/ # Shared modules
components/ # Reusable buttons, cards
hooks/ # useLocalStorage, useFetch
utils/ # Helper calculations
pages/ # View entry layouts
app/ # Router configs and providers
index.css # Global style tokens🎯 Section 21 Interview Questions (10+)
1. How do you structure a large-scale React project?
Use a domain-driven, feature-based layout, grouping related components, hooks, and API queries under dedicated feature subdirectories.
2. What is a feature-based folder structure and why is it preferred?
Grouping files by feature domain (e.g., auth, billing) rather than file type (e.g., components, styles). It keeps files localized and easy to find.
3. What are barrel files and what are their trade-offs?
Barrel files (index.js exports) consolidate imports under single filenames. Trade-offs: clean import lines, but they can cause circular dependencies and hinder tree shaking if not configured correctly.
4. What is the difference between CRA and Vite? Why is Vite preferred?
CRA uses Webpack to bundle code on startup. Vite uses native ES Modules during development to render files instantly, compiling bundles using Rollup.
5. How do you handle environment variables in a React app?
Store them in .env files prefixed with VITE_ (e.g., VITE_API_URL). Access them in code using import.meta.env.VITE_API_URL.
6. What is ESLint and how do you configure it for a React + TypeScript project?
ESLint is a static code analyzer. Configure it with typescript-eslint plugins to enforce styling rules, verify hook layouts, and prevent compile errors.
7. What is Husky and what pre-commit hooks would you set up?
Husky runs scripts (like eslint check, vitest run) during git commit actions, preventing broken changes from pushing to main branches.
8. How do you set up absolute imports in a React + Vite project?
Add resolve.alias configurations in vite.config.js and path definitions inside tsconfig.json (e.g., mapping '@' to '/src').
9. What is a monorepo and when would you use one for React projects?
A single repository containing multiple applications and shared packages. Use it when maintaining web and mobile projects (React Native) that share code.
10. How do you organize shared components vs feature-specific components?
Place generic, non-business elements (e.g., buttons, loaders) in shared/components. Place feature-specific UI (e.g., LoginForm) inside the feature's components folder.
Resources & Next Steps
Recommended Documentation
Official resources to deepen your understanding.
Join the Community
Connect and follow for regular web & mobile tutorials.
Conclusion
Mastering React in 2026 is about understanding how components render, how data flows, and where application state belongs. By focusing on the core fundamentals-clean components, proper state placement, and effective side-effect management-you lay the foundation for web and mobile development excellence.
Whether you are preparing for technical interviews, refactoring legacy class components, or initializing a greenfield project with React 19, keep these principles close. Keep coding, keep experimenting, and remember: composition always wins.
You've completed the guide! Go build something great.
Frequently Asked Questions
Build a Consistent Coding Habit
Stop guessing and start building. This e-book provides practical strategies, exercises, and routines to help you code regularly and improve steadily.
Get E-BookMaster Unfamiliar Codebases
Struggling to make sense of someone else's code? Learn practical strategies to navigate, analyze, and master unfamiliar codebases with confidence.
Get E-Book
💬 Discussion