React Fundamentals

1. Core Concepts

Q: What is the Virtual DOM?
Diffing and Reconciliation.
Basic Concept
// React Element (Virtual DOM Object)
const element = {
  type: 'h1',
  props: { className: 'greeting', children: 'Hello' }
};
// Lightweight JS object, not a real DOM node.

The Virtual DOM is a lightweight copy of the actual DOM in memory. When state changes:

  1. React creates a new Virtual DOM tree.
  2. It compares (diffs) it with the previous tree.
  3. It calculates the minimum number of changes needed.
  4. It updates the real DOM in a batch (Reconciliation).
Q: What is JSX?
Syntax Extension for JavaScript.

JSX stands for JavaScript XML. It allows us to write HTML-like syntax directly in JavaScript. It is syntactic sugar that transpilers (like Babel) convert into React.createElement() calls.

Q: Props vs State
Immutable vs Mutable.
Q: What are Synthetic Events?
Cross-browser wrapper.

React doesn't attach event handlers to nodes directly. Instead, it uses a single event listener at the root (Event Delegation) and wraps native browser events in SyntheticEvent objects. This ensures consistent behavior across different browsers.

Q: Explain the Component Lifecycle (Class vs Functional).
Mounting, Updating, Unmounting.

Class Components:

Functional Components (Hooks):

2. Hooks Basics

Q: Explain the useEffect dependency array.
When does it run?
Basic Implementation
useEffect(() => {
  console.log("Runs on every render");
});

useEffect(() => {
  console.log("Runs once on mount");
}, []);

useEffect(() => {
  console.log("Runs when count changes");
}, [count]);
Real World Example (Data Fetching)
useEffect(() => {
  let ignore = false;
  async function fetchUser() {
    const res = await api.get(userId);
    if (!ignore) setUser(res);
  }
  fetchUser();
  return () => { ignore = true; }; // Cleanup race conditions
}, [userId]);
Show Answer
  • useEffect(fn): Runs after every render.
  • useEffect(fn, []): Runs only once (on mount).
  • useEffect(fn, [prop, state]): Runs on mount AND whenever prop or state changes.

Cleanup Function: Returned from the effect. Runs before the component unmounts or before the effect re-runs.

useEffect(() => {
  const timer = setInterval(tick, 1000);
  return () => clearInterval(timer); // Cleanup
}, []);
Q: Why must Hooks be at the top level?
Order matters.
Basic Implementation
// Correct
function Component() {
  const [val, setVal] = useState(0);
  if (val > 0) { ... }
}

// Incorrect (Breaks React)
function Component() {
  if (condition) {
    const [val, setVal] = useState(0); // Hook inside condition
  }
}
Real World Example (Linting)
// ESLint plugin 'eslint-plugin-react-hooks' enforces this rule.
// Error: React Hook "useState" is called conditionally.
Show Answer

React relies on the order of hooks to track state. If you put a hook inside an if statement, the order might change between renders, corrupting the state.

Q: What is "Prop Drilling" and how do you avoid it?
Passing data through many layers.
Basic Implementation
// Drilling
<GrandParent user={user} />
  <Parent user={user} />
    <Child user={user} /> // Only Child needs it
Real World Example (Context API)
// Solution: Context
const UserContext = createContext();
// ...
<UserContext.Provider value={user}>...</UserContext.Provider>
// ...
const user = useContext(UserContext); // Access directly in Child
Show Answer

Passing props through intermediate components that don't need them.

Fixes:

  • Composition: Pass components as children.
  • Context: For global data.
  • State Managers: Redux/Zustand.
Q: What is the "Key" prop and why is it important?
Lists and Identity.
Basic Implementation
// Bad (Index as key)
{items.map((item, index) => <li key={index}>{item}</li>)}

// Good (Unique ID)
{items.map(item => <li key={item.id}>{item.name}</li>)}
Real World Example (Reordering)
// If you delete the first item, React needs keys to know
// which DOM nodes to keep. With index keys, it might update
// the wrong component state.
Show Answer

It helps React identify which items have changed, are added, or are removed. Using index as a key is bad if the list order changes, as it causes bugs with component state.

Q: What is "Lifting State Up"?
Sharing state between siblings.
Basic Implementation
function Parent() {
  const [text, setText] = useState(""); // State lifted here
  return (
    <>
      <Input value={text} onChange={setText} />
      <Display text={text} />
    </>
  );
}
Real World Example (Filters)
// FilterBar and ProductList are siblings.
// Filter state lives in their parent (ProductPage) so both can access it.
Show Answer

Moving state to the closest common ancestor of two components that need to share that state.

Q: What are "Controlled Components"?
Forms and State.
Basic Implementation
const [val, setVal] = useState("");
<input value={val} onChange={e => setVal(e.target.value)} />
// React controls the value
Real World Example (Validation)
// Instant validation feedback
const handleChange = (e) => {
  const newValue = e.target.value;
  if (newValue.length <= 10) setValue(newValue); // Enforce limit
};
Show Answer

Form inputs whose value is controlled by React state. The "source of truth" is the React state, not the DOM.

Q: What is the difference between `useEffect` and `useLayoutEffect`?
Timing of execution.
Basic Implementation
// useEffect: Runs after paint (Async)
useEffect(() => { console.log("Visible"); });

// useLayoutEffect: Runs before paint (Sync)
useLayoutEffect(() => { console.log("Blocking"); });
Real World Example (Measurements)
// Measuring DOM element size before user sees it
useLayoutEffect(() => {
  const { height } = ref.current.getBoundingClientRect();
  setHeight(height);
}, []);
Show Answer

useEffect runs after the paint (async). useLayoutEffect runs synchronously after DOM mutations but before the paint. Use useLayoutEffect only if you need to measure DOM elements to prevent visual flickering.

3. Components & Props

Q: Functional vs Class Components
Evolution.
Basic Implementation
// Class
class Welcome extends React.Component {
  render() { return <h1>Hello, {this.props.name}</h1>; }
}

// Functional
function Welcome({ name }) {
  return <h1>Hello, {name}</h1>;
}
Real World Example (Hooks)
// Functional components can use Hooks (useState, useEffect)
// Class components cannot.
Show Answer

Class: OOP, `this`, lifecycle methods, verbose. Functional: Functions, Hooks, simpler, modern standard.

Q: What is JSX?
Syntax Extension.
Basic Implementation
const element = <h1>Hello</h1>;
// Transpiles to:
const element = React.createElement('h1', null, 'Hello');
Real World Example (Expressions)
// Embedding JS expressions
const element = <h1>Hello, {formatName(user)}</h1>;
Show Answer

JavaScript XML. Syntactic sugar for React.createElement(type, props, ...children).

Q: What are Fragments?
<>...</>
Basic Implementation
return (
  <React.Fragment>
    <ChildA />
    <ChildB />
  </React.Fragment>
);
// Short syntax: <>...</>
Real World Example (Table Rows)
// <div> cannot be a child of <tr>
function Columns() {
  return (
    <>
      <td>Hello</td>
      <td>World</td>
    </>
  );
}
Show Answer

A way to group a list of children without adding extra nodes to the DOM. <React.Fragment> or <>.

Q: `children` prop
Composition.
Basic Implementation
function Box({ children }) {
  return <div className="box">{children}</div>;
}
// Usage
<Box>
  <p>Content inside</p>
</Box>
Real World Example (Layouts)
function Layout({ children }) {
  return (
    <div>
      <Header />
      <main>{children}</main>
      <Footer />
    </div>
  );
}
Show Answer

A special prop that allows passing components or elements inside another component's opening and closing tags.

Q: Default Props
Fallback values.
Basic Implementation
function Button({ color = "blue" }) {
  return <button className={color}>Click</button>;
}
Real World Example (Old Way)
// Class components used defaultProps
class Button extends React.Component { ... }
Button.defaultProps = { color: 'blue' };
Show Answer

You can define default values for props using default parameters in the function signature. function Comp({ name = "Guest" }).

Q: PureComponent
Class optimization.
Basic Implementation
class MyComponent extends React.PureComponent {
  // Automatically implements shouldComponentUpdate
  // with shallow prop comparison
}
Real World Example (Functional Equivalent)
const MyComponent = React.memo(function MyComponent(props) {
  // Only re-renders if props change
});
Show Answer

A class component that implements shouldComponentUpdate with a shallow prop and state comparison. Functional equivalent is React.memo.

Q: Synthetic Events
Cross-browser wrapper.
Basic Implementation
function handleClick(e) {
  e.preventDefault(); // Works identically in all browsers
  console.log(e.nativeEvent); // Access underlying browser event
}
Real World Example (Pooling - Historical)
// Before React 17, events were pooled (reused).
// e.persist() was needed to use event async.
// React 17+ removed pooling, so this is less of an issue now.
Show Answer

React's cross-browser wrapper around the browser's native event. It ensures events behave consistently across different browsers.

Q: Why is `setState` async?
Batching.
Basic Implementation
const [count, setCount] = useState(0);
const handleClick = () => {
  setCount(count + 1);
  console.log(count); // Still 0! Update hasn't happened yet.
};
Real World Example (Performance)
// React batches multiple updates into a single re-render
// to avoid unnecessary layout thrashing.
setCount(c => c + 1);
setFlag(true);
// Triggers only ONE re-render.
Show Answer

React batches state updates for performance. It doesn't update the state immediately but schedules an update.

Q: `setState` with function
Previous state.
Basic Implementation
// Wrong if called multiple times rapidly
setCount(count + 1);

// Correct
setCount(prevCount => prevCount + 1);
Real World Example (Toggle)
const toggle = () => setIsOpen(prev => !prev);
// Safe regardless of how many times it's clicked quickly
Show Answer

When the new state depends on the old state, pass a function: setCount(prev => prev + 1) to ensure you have the latest value.

Q: Uncontrolled Components
Refs.
Basic Implementation
function Form() {
  const inputRef = useRef();
  const handleSubmit = () => {
    alert(inputRef.current.value); // Access DOM directly
  };
  return <input ref={inputRef} />;
}
Real World Example (File Inputs)
// File inputs are always uncontrolled in React
<input type="file" ref={fileInputRef} />
Show Answer

Form inputs where the DOM handles the data, accessed via Refs, instead of React state.

Q: `useRef` Hook
Persistence without render.
Show Answer

Returns a mutable ref object. Changing ref.current does not trigger a re-render. Used for DOM access or storing mutable values.

Q: `useContext` Hook
Consuming context.
Show Answer

Accepts a context object and returns the current context value. Subscribes the component to context changes.

Q: `useReducer` Hook
Complex state logic.
Show Answer

Alternative to useState. Accepts a reducer of type (state, action) => newState. Good for complex state transitions.

Q: Custom Hooks
Reuse logic.
Show Answer

JavaScript functions that start with "use" and can call other hooks. Allow sharing stateful logic between components.

Q: Rules of Hooks
Two main rules.
Show Answer
  1. Only call Hooks at the top level (not inside loops/conditions).
  2. Only call Hooks from React function components or custom hooks.
Q: Lifecycle: Mounting
Birth.
Show Answer

Class: constructor -> render -> componentDidMount. Functional: Function body -> useEffect(() => {}, []).

Q: Lifecycle: Updating
Growth.
Show Answer

Class: render -> componentDidUpdate. Functional: Function body -> useEffect(() => {}) or useEffect with deps.

Q: Lifecycle: Unmounting
Death.
Show Answer

Class: componentWillUnmount. Functional: useEffect cleanup function.

Q: `dangerouslySetInnerHTML`
XSS risk.
Show Answer

React's replacement for innerHTML. Risky because it can expose users to Cross-Site Scripting (XSS) attacks.

Q: Inline Styles
Object syntax.
Show Answer

Styles are passed as an object with camelCased properties. style={{ backgroundColor: 'red' }}.

Q: CSS Modules
Scoped CSS.
Show Answer

A CSS file where all class names are scoped locally by default. Imported as an object: import styles from './App.module.css'.

Q: Styled Components
CSS-in-JS.
Show Answer

Library for writing actual CSS code to style components. Uses tagged template literals.

Q: Conditional Rendering
If/Else, Ternary, &&.
Show Answer

Rendering different UI based on state. {isLoggedIn ? <User/> : <Login/>}.

Q: Lists in React
Map.
Show Answer

Use .map() to transform an array of data into an array of elements.

Q: Why not use index as key?
Reordering issues.
Show Answer

If the list order changes (sorting, filtering, inserting), using index as key can cause React to reuse state for the wrong component.

Q: `htmlFor`
Labels.
Show Answer

Since for is a reserved word in JS, React uses htmlFor for label tags.

Q: `className`
Classes.
Show Answer

Since class is a reserved word in JS, React uses className for CSS classes.

Q: React.StrictMode
Double render.
Show Answer

A tool for highlighting potential problems. In development, it renders components twice to detect side effects.

Q: One-way Data Flow
Unidirectional.
Show Answer

Data flows down from parent to child via props. Children cannot modify parent state directly (must use callbacks).

Q: Component Composition
Building blocks.
Show Answer

Building complex UIs from smaller, independent, reusable components.

Q: Higher-Order Component (HOC)
Function taking component.
Show Answer

A function that takes a component and returns a new component. Used for cross-cutting concerns (logging, auth).

Q: Render Props
Prop as function.
Show Answer

A technique for sharing code between components using a prop whose value is a function. <DataProvider render={data => <Cat data={data}/>} />.

Q: `forwardRef`
Passing refs down.
Show Answer

Allows a component to take a ref passed to it and forward it to a child DOM element.

Q: Portals
Outside DOM hierarchy.
Show Answer

Way to render children into a DOM node that exists outside the DOM hierarchy of the parent component (e.g., Modals, Tooltips).

Q: Error Boundaries
Catching crashes.
Show Answer

Class components that catch JS errors in their child component tree, log errors, and display a fallback UI.

Q: Lazy Loading
React.lazy.
Show Answer

Loading components only when they are needed. const OtherComponent = React.lazy(() => import('./OtherComponent'));.

Q: Suspense
Loading state.
Show Answer

Component that lets you display a fallback (like a spinner) while children are finishing loading (e.g., lazy components or data).

Q: Profiler
Measuring performance.
Show Answer

React DevTools Profiler measures how often a React application renders and what the "cost" of rendering is.

Q: Reconciliation
Diffing algorithm.
Show Answer

The process through which React updates the DOM. It compares the new Virtual DOM with the old one and applies changes.

Q: Fiber
New engine.
Show Answer

The new reconciliation engine in React 16. Enables features like concurrency and suspense by splitting work into chunks.