Skip to main content

πŸ“˜ React Components (Functional & Class Basics) β€” Complete Theory Guide


1. πŸ”Ή Introduction

βœ… What are Components?

In React, components are the fundamental building blocks of a UI. They are reusable, independent pieces of code that return UI elements. There are two main types:
  • Functional Components (modern, preferred)
  • Class Components (legacy but still important for understanding React evolution)

πŸ’‘ Why Components are Important

  • Enable modular architecture
  • Promote code reuse
  • Improve maintainability
  • Allow separation of concerns
  • Help manage UI logic efficiently

πŸ“ When & Why We Use Components

Use components when:
  • UI can be broken into smaller parts (e.g., Navbar, Card, Button)
  • You want reusable UI patterns
  • You need to isolate logic (state, effects)
πŸ‘‰ Example: Instead of writing a full page in one file, split into:
  • <Header />
  • <Sidebar />
  • <ProductCard />

2. βš™οΈ Concepts / Internal Workings


πŸ”Ή 2.1 Functional Components

A functional component is simply a JavaScript function that returns JSX.
function Welcome() {
  return <h1>Hello, World!</h1>;
}

Key Characteristics:

  • Stateless (initially), but now use Hooks
  • Lightweight and faster
  • Easier to read and test

πŸ”Ή 2.2 Class Components

A class component is a JavaScript class that extends React.Component.
import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

Key Characteristics:

  • Uses lifecycle methods
  • Has this binding
  • Manages state via this.state

πŸ”Ή 2.3 JSX β†’ React Elements β†’ Virtual DOM

Flow:

  1. JSX is written
  2. Transpiled to React.createElement
  3. Creates Virtual DOM
  4. React compares (Diffing)
  5. Updates real DOM (Reconciliation)
const element = <h1>Hello</h1>;

// becomes:
React.createElement('h1', null, 'Hello');

πŸ”Ή 2.4 Props (Input to Components)

Props = Read-only data passed from parent to child.
function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

πŸ”Ή 2.5 State (Internal Data)

State is mutable data inside a component.

Functional (Hooks):

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Class:

this.state = { count: 0 };
this.setState({ count: this.state.count + 1 });

πŸ”Ή 2.6 Lifecycle (Class Components)

Important lifecycle methods:
PhaseMethod
MountingcomponentDidMount
UpdatingcomponentDidUpdate
UnmountingcomponentWillUnmount

πŸ”Ή 2.7 Functional Alternative to Lifecycle (Hooks)

  • useEffect() replaces lifecycle methods
useEffect(() => {
  console.log("Component Mounted");
}, []);

πŸ”Ή 2.8 Component Tree & Re-rendering

  • React builds a component tree
  • Re-renders happen when:
    • Props change
    • State changes

πŸ”Ή 2.9 Relationship with Other React Features

FeatureRelationship
HooksUsed in functional components
Context APIShare data across components
ReduxExternal state management
React RouterComponent-based navigation

3. πŸ§ͺ Syntax & Examples


πŸ”Ή 3.1 Basic Functional Component

function App() {
  return <h1>My App</h1>;
}

πŸ”Ή 3.2 Arrow Function Component

const App = () => <h1>Hello</h1>;

πŸ”Ή 3.3 Component with Props

const User = ({ name }) => {
  return <h2>{name}</h2>;
};

πŸ”Ή 3.4 Nested Components

function App() {
  return (
    <div>
      <Header />
      <Footer />
    </div>
  );
}

πŸ”Ή 3.5 Conditional Rendering

function Status({ isLoggedIn }) {
  return isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>;
}

πŸ”Ή 3.6 List Rendering

const items = ['A', 'B', 'C'];

items.map((item, index) => <li key={index}>{item}</li>);

πŸ”Ή 3.7 Class Component Example

class Counter extends React.Component {
  state = { count: 0 };

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        {this.state.count}
      </button>
    );
  }
}

πŸ”Ή 3.8 Controlled Component

function Input() {
  const [value, setValue] = useState("");

  return (
    <input value={value} onChange={(e) => setValue(e.target.value)} />
  );
}

4. ⚠️ Edge Cases / Common Mistakes


❌ 4.1 Mutating State Directly

// WRONG
state.count = 1;
πŸ‘‰ Always use setter:
setCount(1);

❌ 4.2 Missing key in Lists

items.map(item => <li>{item}</li>) // ❌
πŸ‘‰ Fix:
items.map(item => <li key={item}>{item}</li>)

❌ 4.3 Infinite Re-renders

setCount(count + 1); // inside render ❌

❌ 4.4 this Binding Issues (Class)

this.handleClick = this.handleClick.bind(this);

❌ 4.5 Incorrect useEffect Dependencies

useEffect(() => {
  fetchData();
}, []); // missing dependencies ❌

❌ 4.6 Re-rendering All Components

  • Happens when parent state updates unnecessarily
πŸ‘‰ Fix:
  • Use React.memo
  • Split components

5. βœ… Best Practices


πŸ”Ή 5.1 Prefer Functional Components

  • Cleaner
  • Hooks-based
  • Future-proof

πŸ”Ή 5.2 Keep Components Small & Focused

  • One responsibility per component

πŸ”Ή 5.3 Use Destructuring

const Card = ({ title }) => <h1>{title}</h1>;

πŸ”Ή 5.4 Use Proper Naming

  • PascalCase for components:
    • UserCard
    • Navbar

πŸ”Ή 5.5 Avoid Inline Functions (Performance)

<button onClick={() => doSomething()} />
πŸ‘‰ Use:
const handleClick = () => doSomething();

πŸ”Ή 5.6 Use Memoization

export default React.memo(Component);

πŸ”Ή 5.7 Avoid Prop Drilling

πŸ‘‰ Use:
  • Context API
  • State management tools

πŸ”Ή 5.8 Use Keys Properly

  • Never use index unless necessary
  • Use unique IDs

πŸ”Ή 5.9 Optimize Re-renders

  • useMemo
  • useCallback

πŸ”Ή 5.10 Folder Structure

/components
  /Button
    Button.jsx
    Button.css

πŸ“Œ Summary

  • Components are the core of React architecture
  • Functional components + Hooks are the modern standard
  • Class components are important for legacy understanding
  • Proper structure and optimization lead to scalable apps

Below is a senior-level conceptual interview set on React Components (Functional & Class Basics) β€” focused on depth, internal behavior, trade-offs, and real-world thinking.

🧠 Advanced React Components β€” Interview Questions & Answers


1. Why did React shift from Class Components to Functional Components with Hooks?

βœ… Strong Answer

The shift was driven by simplicity, composability, and better logic reuse.

πŸ” Key Reasons

  1. Separation of Concerns
    • Class components split logic across lifecycle methods
    • Hooks allow grouping related logic together
  2. Avoid this Complexity
    • Class components require binding
    • Functional components eliminate this
  3. Better Code Reuse
    • Hooks replace HOCs and render props
  4. Less Boilerplate

πŸ’‘ Example Comparison

Class (fragmented logic):
componentDidMount() {
  fetchData();
}

componentDidUpdate() {
  fetchData();
}
Functional (cohesive logic):
useEffect(() => {
  fetchData();
}, [dependency]);

βš–οΈ Trade-off

  • Hooks introduce dependency array complexity
  • Requires understanding of closures

2. How does React internally treat Functional vs Class components?

βœ… Strong Answer

Internally, both are treated as units that produce React elements, but:
  • Class Components β†’ instantiated with new
  • Functional Components β†’ invoked as plain functions

πŸ” Internal Differences

AspectFunctionalClass
ExecutionFunction callClass instance
State storageHook list (linked to fiber)Instance (this.state)
LifecycleuseEffect hooksLifecycle methods

🧠 Fiber Insight

React stores hooks in a linked list inside Fiber nodes, maintaining order across renders.

3. Why must Hooks be called unconditionally and in the same order?

βœ… Strong Answer

React relies on call order to map hooks to internal state slots.

πŸ” Internal Reason

React does NOT track hooks by name β€” it tracks by position.
// ❌ WRONG
if (condition) {
  useEffect(() => {});
}

πŸ’‘ Why it breaks?

  • On next render, hook order changes
  • React mismatches state

4. What actually triggers a component re-render?

βœ… Strong Answer

A component re-renders when:
  1. State changes
  2. Props change
  3. Parent re-renders
  4. Context changes

πŸ” Important Insight

React does NOT deeply compare values β€” it relies on reference equality.
setState({}) // always new reference β†’ re-render

βš–οΈ Optimization

  • React.memo
  • useMemo
  • useCallback

5. Why is direct state mutation a critical issue?

βœ… Strong Answer

React relies on immutability for change detection.

πŸ” Problem

state.count = 1; // ❌ no re-render
React cannot detect the change because:
  • Reference is unchanged

βœ… Correct

setCount(prev => prev + 1);

6. How does React reconcile component trees?

βœ… Strong Answer

React uses a diffing algorithm (Reconciliation):
  1. Compare old vs new Virtual DOM
  2. Identify minimal changes
  3. Update real DOM efficiently

πŸ” Key Assumptions

  • Elements of different types β†’ replace
  • Keys help track identity

7. Why are keys critical in list rendering?

βœ… Strong Answer

Keys help React preserve component identity across renders.

πŸ” Problem Without Keys

items.map((item, index) => <Item key={index} />)
  • Causes incorrect DOM reuse
  • Leads to bugs (especially in forms)

πŸ’‘ Real Issue

  • Input values shifting unexpectedly

8. Explain the difference between controlled and uncontrolled components.

βœ… Strong Answer

TypeControlledUncontrolled
Data SourceReact stateDOM
ControlFull controlLess control

πŸ’‘ Example

<input value={value} onChange={...} />

βš–οΈ Trade-off

  • Controlled β†’ predictable but verbose
  • Uncontrolled β†’ simpler but less flexible

9. What are the hidden pitfalls of useEffect?

βœ… Strong Answer

  1. Stale closures
  2. Missing dependencies
  3. Infinite loops

πŸ’‘ Example

useEffect(() => {
  console.log(count);
}, []); // stale value

βœ… Fix

useEffect(() => {
  console.log(count);
}, [count]);

10. Why do functions inside components cause performance issues?

βœ… Strong Answer

Functions are recreated on every render β†’ new reference β†’ triggers child re-renders.
<button onClick={() => doSomething()} />

βœ… Fix

const handleClick = useCallback(() => {}, []);

11. How does React.memo work internally?

βœ… Strong Answer

  • Performs shallow comparison of props
  • Skips re-render if props unchanged

⚠️ Limitation

<Child obj={{ a: 1 }} />
  • Always re-renders due to new reference

12. When would you still use Class Components today?

βœ… Strong Answer

  • Legacy codebases
  • Error boundaries (before hooks alternative)
componentDidCatch(error, info) {}

βš–οΈ Trade-off

  • More verbose
  • Less composable

13. Explain lifting state up and its trade-offs.

βœ… Strong Answer

Moving shared state to the closest common ancestor.

πŸ’‘ Problem

  • Leads to prop drilling

βœ… Alternative

  • Context API
  • State libraries

14. What is prop drilling and how do you avoid it?

βœ… Strong Answer

Passing props through multiple layers unnecessarily.
<App β†’ A β†’ B β†’ C β†’ D />

βœ… Solutions

  • Context API
  • Redux / Zustand

15. How do closures affect React components?

βœ… Strong Answer

Closures can capture stale state values.
setTimeout(() => {
  console.log(count);
}, 1000);

βœ… Fix

setCount(prev => prev + 1);

16. Why is component composition preferred over inheritance in React?

βœ… Strong Answer

React promotes composition for flexibility.

πŸ’‘ Example

<Card>
  <Button />
</Card>

βš–οΈ Why not inheritance?

  • Tight coupling
  • Less reusable

17. How does React batch state updates?

βœ… Strong Answer

React groups multiple updates into a single render for performance.
setCount(1);
setCount(2);
β†’ One render

πŸ” React 18+

  • Automatic batching even in async code

18. What are render phases vs commit phases?

βœ… Strong Answer

PhaseDescription
RenderCalculate changes
CommitApply to DOM

πŸ” Insight

  • Render phase can be interrupted
  • Commit phase is synchronous

19. Why can excessive component re-rendering become a bottleneck?

βœ… Strong Answer

Because React:
  • Re-executes component functions
  • Recalculates Virtual DOM

πŸ” Real-world Impact

  • Slow UI in large trees

βœ… Fix

  • Memoization
  • Splitting components

20. How do you decide component boundaries in a real application?

βœ… Strong Answer

Based on:
  1. Reusability
  2. Separation of concerns
  3. Performance isolation

πŸ’‘ Bad Design

  • One giant component

πŸ’‘ Good Design

  • Small, focused, composable components

πŸ“Œ Final Takeaway

Senior-level understanding of components is about:
  • Thinking in render cycles
  • Understanding React internals (Fiber, reconciliation)
  • Managing performance trade-offs
  • Designing scalable component architecture

Below is a senior-level MCQ set (18 questions) on React Components (Functional & Class Basics). Each question targets deep understanding, edge cases, and real-world behavior.

🧠 Advanced React Components β€” MCQs


1. What happens when you update state with the same value?

const [count, setCount] = useState(0);
setCount(0);

Options:

A. Component always re-renders B. Component never re-renders C. React may skip re-render using Object.is comparison D. React throws an error

βœ… Correct Answer: C

πŸ’‘ Explanation:

React uses Object.is comparison. If the value is identical, React bails out of re-render.

❌ Why others are wrong:

  • A: Incorrect β€” React optimizes unnecessary renders
  • B: Not always true (edge cases like forced updates)
  • D: No error occurs

2. What is the output?

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(1);
  }, []);

  console.log(count);
  return null;
}

Options:

A. Logs 0 B. Logs 1 C. Logs 0 then 1 D. Infinite loop

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Initial render β†’ logs 0
  • Effect runs after render β†’ updates state β†’ re-render β†’ logs 1

❌ Others:

  • A/B: Ignore lifecycle timing
  • D: No dependency loop

3. Why is this problematic?

useEffect(() => {
  fetchData();
}, []);

Options:

A. It runs too many times B. It may use stale variables C. It blocks rendering D. It causes memory leaks always

βœ… Correct Answer: B

πŸ’‘ Explanation:

The empty dependency array can cause stale closure issues if fetchData depends on changing values.

4. What happens here?

const obj = { a: 1 };
setState(obj);
setState(obj);

Options:

A. Two re-renders B. One re-render C. No re-render D. Error

βœ… Correct Answer: B

πŸ’‘ Explanation:

Same reference β†’ React batches updates β†’ single re-render.

5. What is the issue with index as key?

items.map((item, index) => <Item key={index} />)

Options:

A. Performance issue only B. Causes incorrect DOM reuse C. Causes syntax error D. Prevents rendering

βœ… Correct Answer: B

πŸ’‘ Explanation:

Index keys break component identity, causing UI bugs during reorder.

6. What happens when parent re-renders?

Options:

A. Only changed children render B. All children render by default C. React skips all children D. Only stateful children render

βœ… Correct Answer: B

πŸ’‘ Explanation:

React re-runs all child components unless optimized.

7. What is wrong here?

if (condition) {
  useEffect(() => {});
}

Options:

A. Nothing B. Causes memory leak C. Breaks hook order D. Slows performance

βœ… Correct Answer: C

πŸ’‘ Explanation:

Hooks must be called in the same order every render.

8. Why does this re-render child?

<Child data={{ a: 1 }} />

Options:

A. Because object is mutable B. New reference each render C. React deep compares D. Child forces update

βœ… Correct Answer: B


9. What happens in this case?

setCount(count + 1);
setCount(count + 1);

Options:

A. +2 increment B. +1 increment C. Infinite loop D. No change

βœ… Correct Answer: B

πŸ’‘ Explanation:

Both updates use same stale value.

10. Correct fix?

Options:

A. setCount(count + 2) B. setCount(prev => prev + 1) twice C. setCount(() => count + 1) D. UseEffect

βœ… Correct Answer: B


11. Why is this inefficient?

<button onClick={() => handleClick()} />

Options:

A. Syntax error B. Recreates function every render C. Blocks UI D. Causes memory leak

βœ… Correct Answer: B


12. What does React.memo NOT handle well?

Options:

A. Primitive props B. Stable references C. Inline objects/functions D. Static components

βœ… Correct Answer: C


13. What happens here?

const [state, setState] = useState({ count: 0 });
setState({ count: 0 });

Options:

A. No re-render B. Re-render occurs C. Error D. Infinite loop

βœ… Correct Answer: B

πŸ’‘ Explanation:

New object reference β†’ triggers render.

14. Why is this unsafe?

state.count++;
setState(state);

Options:

A. Syntax issue B. Mutation breaks React detection C. Causes crash D. Async issue

βœ… Correct Answer: B


15. What is true about class vs functional?

Options:

A. Class is faster B. Functional supports hooks C. Class supports hooks D. Functional cannot manage state

βœ… Correct Answer: B


16. What happens during reconciliation?

Options:

A. Full DOM replacement B. Minimal updates via diffing C. No updates D. Random updates

βœ… Correct Answer: B


17. What is the problem here?

useEffect(() => {
  setCount(count + 1);
}, [count]);

Options:

A. Runs once B. Infinite loop C. No update D. Error

βœ… Correct Answer: B


18. Why prefer composition over inheritance?

Options:

A. Less code B. More flexibility and reuse C. Required by React D. Better performance only

βœ… Correct Answer: B


πŸ“Œ Final Insight

These questions test:
  • Render cycle understanding
  • Hook behavior & pitfalls
  • Reconciliation & identity
  • Performance reasoning
  • Real-world debugging mindset

Below is a senior-level coding problem set (18 problems) focused on React Components (Functional & Class Basics). Each problem simulates real-world scenarios, emphasizes thinking, and includes edge cases + reasoning.

🧠 Advanced React Component Coding Problems


1. πŸ”„ Smart Counter with Sync Issues

🧩 Problem

Build a counter that:
  • Increments correctly even with rapid clicks
  • Logs correct value after async delay

⚠️ Constraints

  • Avoid stale state
  • Must handle async updates

βœ… Expected Behavior

  • Clicking 3 times β†’ count = 3
  • Console logs correct count

⚠️ Edge Cases

  • Rapid clicks
  • Async delays

πŸ’‘ Solution

const Counter = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(prev => prev + 1);

    setTimeout(() => {
      console.log("Latest:", count); // stale
    }, 1000);
  };

  return <button onClick={handleClick}>{count}</button>;
};

🧠 Fix Explanation

Use ref to avoid stale closure:
const countRef = useRef(count);
useEffect(() => {
  countRef.current = count;
}, [count]);

2. πŸ” Prevent Unnecessary Re-renders

🧩 Problem

Optimize a child component so it doesn’t re-render unnecessarily.

Constraints

  • Parent updates frequently

πŸ’‘ Solution

const Child = React.memo(({ data }) => {
  console.log("Rendered");
  return <div>{data.value}</div>;
});

🧠 Explanation

Use React.memo + stable props (useMemo)

3. 🧠 Derived State Bug

Problem

Sync prop β†’ state without causing inconsistency.

Edge Case

  • Prop updates asynchronously

❌ Bad

const [value, setValue] = useState(props.value);

βœ… Solution

useEffect(() => {
  setValue(props.value);
}, [props.value]);

4. πŸ” Search with Debounce

Problem

Create search input with debounce.

Constraints

  • Avoid excessive API calls

πŸ’‘ Solution

useEffect(() => {
  const id = setTimeout(() => {
    fetchResults(query);
  }, 500);

  return () => clearTimeout(id);
}, [query]);

5. πŸ“¦ Dynamic Form Builder

Problem

Render form fields dynamically based on config.

Edge Case

  • Unknown field types

Solution Idea

Use component mapping:
const components = {
  text: TextInput,
  checkbox: Checkbox,
};

6. πŸ” Controlled vs Uncontrolled Hybrid

Problem

Input should:
  • Work controlled OR uncontrolled

Solution

const isControlled = value !== undefined;

7. πŸ”„ Infinite Loop Debugging

Problem

Fix infinite re-render:
useEffect(() => {
  setData(fetchData());
}, [data]);

Solution

  • Remove data dependency
  • Use proper trigger

8. 🧩 Compound Components Pattern

Problem

Build <Tabs> system:
<Tabs>
  <Tabs.List />
  <Tabs.Panel />
</Tabs>

Solution Idea

Use Context API

9. πŸ“Š Expensive Calculation Optimization

Problem

Prevent heavy recalculation

Solution

const result = useMemo(() => expensiveFn(data), [data]);

10. πŸ” Shared State Between Siblings

Problem

Two components share state

Solution

Lift state up OR Context

11. 🧡 Async Data Race Condition

Problem

Avoid outdated API results overriding new ones

Solution

let active = true;

if (active) setData(result);

return () => active = false;

12. 🧠 Custom Hook Extraction

Problem

Extract reusable logic (e.g., window resize)

Solution

function useWindowSize() {}

13. 🎯 Conditional Rendering Trap

Problem

Prevent component losing state when hidden

❌ Bad

{show && <Component />}

βœ… Solution

Keep mounted + toggle visibility

14. πŸ”‘ List Reordering Bug

Problem

Fix UI glitch when reordering items

Solution

Use stable unique keys (IDs)

15. πŸ§ͺ Error Boundary Implementation

Problem

Catch runtime errors

Solution (Class Only)

class ErrorBoundary extends React.Component {
  componentDidCatch(error) {}
}

16. 🧩 Component Composition Refactor

Problem

Refactor large component into smaller ones

Solution

  • Split by responsibility
  • Extract reusable pieces

17. ⚑ Batch Updates Understanding

Problem

Explain why:
setCount(1);
setCount(2);
β†’ Only one render

Solution

React batching

18. πŸ”„ Function Identity Bug

Problem

Child re-renders due to function prop

Solution

const fn = useCallback(() => {}, []);

πŸ“Œ Final Insight

These problems test:
  • State correctness under async conditions
  • Render optimization thinking
  • Component architecture design
  • Real-world debugging skills

Below are 18 senior-level debugging challenges based on React Components (functional & class basics). Each mirrors real production bugs β€” subtle, non-trivial, and rooted in React behavior.

🐞 Advanced React Debugging Challenges


1. πŸ” Stale Closure in Async Callback

❌ Buggy Code

function Counter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setTimeout(() => {
      console.log(count);
    }, 1000);
  };

  return <button onClick={handleClick}>{count}</button>;
}

❗ What’s Wrong

Logs stale count value.

πŸ€” Why It Happens

Closure captures value at render time, not latest state.

βœ… Fix

const countRef = useRef(count);

useEffect(() => {
  countRef.current = count;
}, [count]);

setTimeout(() => {
  console.log(countRef.current);
}, 1000);

🧠 Best Practice

  • Use useRef or functional updates for async logic

2. πŸ”„ Infinite useEffect Loop

❌ Code

useEffect(() => {
  setData(fetchData());
}, [data]);

❗ Problem

Infinite re-render loop

πŸ€” Why

  • setData updates data
  • dependency triggers effect again

βœ… Fix

useEffect(() => {
  setData(fetchData());
}, []);

🧠 Best Practice

  • Avoid updating dependencies inside effect

3. πŸ“¦ Re-render due to Object Props

❌ Code

<Child config={{ theme: "dark" }} />

❗ Problem

Child re-renders every time

πŸ€” Why

New object reference each render

βœ… Fix

const config = useMemo(() => ({ theme: "dark" }), []);
<Child config={config} />

🧠 Best Practice

  • Memoize objects/functions passed as props

4. πŸ”‘ List Reordering Bug

❌ Code

items.map((item, index) => <Item key={index} />)

❗ Problem

UI glitches on reorder

πŸ€” Why

Index doesn’t preserve identity

βœ… Fix

items.map(item => <Item key={item.id} />)

🧠 Best Practice

  • Always use stable unique keys

5. 🧠 Incorrect State Mutation

❌ Code

state.count++;
setState(state);

❗ Problem

Component may not re-render

πŸ€” Why

Reference unchanged β†’ React doesn’t detect change

βœ… Fix

setState(prev => ({ ...prev, count: prev.count + 1 }));

6. ⚑ Double State Update Bug

❌ Code

setCount(count + 1);
setCount(count + 1);

❗ Problem

Only increments once

πŸ€” Why

Both use same stale value

βœ… Fix

setCount(prev => prev + 1);
setCount(prev => prev + 1);

7. 🧩 Missing Dependency in useEffect

❌ Code

useEffect(() => {
  fetchData(userId);
}, []);

❗ Problem

Doesn’t update when userId changes

πŸ€” Why

Dependency missing

βœ… Fix

useEffect(() => {
  fetchData(userId);
}, [userId]);

8. πŸ”„ Function Prop Causing Re-render

❌ Code

<Child onClick={() => doSomething()} />

❗ Problem

Child re-renders unnecessarily

πŸ€” Why

New function reference each render

βœ… Fix

const handleClick = useCallback(() => doSomething(), []);
<Child onClick={handleClick} />

9. πŸ§ͺ useEffect Cleanup Missing

❌ Code

useEffect(() => {
  window.addEventListener("resize", handleResize);
}, []);

❗ Problem

Memory leak

πŸ€” Why

Listener never removed

βœ… Fix

useEffect(() => {
  window.addEventListener("resize", handleResize);
  return () => window.removeEventListener("resize", handleResize);
}, []);

10. 🧠 Derived State Desync

❌ Code

const [value, setValue] = useState(props.value);

❗ Problem

State not updating with props

πŸ€” Why

Initial value only used once

βœ… Fix

useEffect(() => {
  setValue(props.value);
}, [props.value]);

11. πŸ” Conditional Hook Usage

❌ Code

if (isVisible) {
  useEffect(() => {});
}

❗ Problem

Hook order breaks

πŸ€” Why

Hooks must run in same order

βœ… Fix

useEffect(() => {
  if (isVisible) {
    // logic
  }
}, [isVisible]);

12. ⚠️ Expensive Calculation Every Render

❌ Code

const result = expensiveFn(data);

❗ Problem

Performance issue

πŸ€” Why

Runs on every render

βœ… Fix

const result = useMemo(() => expensiveFn(data), [data]);

13. πŸ”„ Component Losing State

❌ Code

{show && <Form />}

❗ Problem

State resets on toggle

πŸ€” Why

Component unmounts

βœ… Fix

<Form hidden={!show} />

14. 🧡 Async Race Condition

❌ Code

useEffect(() => {
  fetch(`/api?q=${query}`).then(setData);
}, [query]);

❗ Problem

Older responses overwrite newer

πŸ€” Why

Async race

βœ… Fix

useEffect(() => {
  let active = true;

  fetch(`/api?q=${query}`).then(res => {
    if (active) setData(res);
  });

  return () => (active = false);
}, [query]);

15. πŸ” Unnecessary Parent Re-renders

❌ Code

const value = { count };

❗ Problem

Triggers children updates

πŸ€” Why

New object each render

βœ… Fix

const value = useMemo(() => ({ count }), [count]);

16. 🧠 setState Async Misunderstanding

❌ Code

setCount(count + 1);
console.log(count);

❗ Problem

Logs old value

πŸ€” Why

State updates are async

βœ… Fix

useEffect(() => {
  console.log(count);
}, [count]);

17. 🧩 Class Component this Issue

❌ Code

handleClick() {
  console.log(this.state);
}

❗ Problem

this undefined

πŸ€” Why

Not bound

βœ… Fix

this.handleClick = this.handleClick.bind(this);
OR
handleClick = () => {}

18. ⚑ React.memo Ineffective

❌ Code

<Child data={{ value: count }} />

❗ Problem

Memo not working

πŸ€” Why

New object every render

βœ… Fix

const data = useMemo(() => ({ value: count }), [count]);

πŸ“Œ Final Takeaways

These bugs reflect real-world issues:
  • Closures & async traps
  • Reference equality pitfalls
  • Hook rules violations
  • Reconciliation misunderstandings
  • Performance bottlenecks

Below is a production-grade machine coding set (18 problems) focused on React Components (Functional & Class Basics). These reflect real-world systems, FAANG-style interviews, and production architecture thinking.

πŸ—οΈ Advanced React Machine Coding Problems


1. 🧠 Smart Autocomplete with Caching

πŸ“Œ Requirements

  • Input field with suggestions
  • Fetch suggestions via API
  • Cache previous queries
  • Highlight matched text

βš™οΈ UI Behavior

  • Debounced typing (300ms)
  • Loading indicator
  • Keyboard navigation (↑ ↓ Enter)

πŸ”„ State/Data Flow

  • query, results, cache, loading, activeIndex

⚠️ Edge Cases

  • Empty input
  • Rapid typing β†’ race conditions
  • Same query repeated

πŸš€ Performance

  • Debounce
  • Memoized cache

πŸ—οΈ Architecture

  • SearchBox
  • SuggestionList
  • useDebounce, useCache

🧠 Approach

  1. Capture input
  2. Debounce API call
  3. Store results in cache
  4. Handle keyboard navigation

2. πŸ“Š Virtualized Infinite List

πŸ“Œ Requirements

  • Render 10k+ items efficiently
  • Infinite scroll loading

βš™οΈ UI Behavior

  • Only visible items rendered
  • Smooth scroll

πŸ”„ State

  • items, scrollTop, visibleRange

⚠️ Edge Cases

  • Fast scroll jumps
  • Dynamic item heights

πŸš€ Performance

  • Windowing (virtualization)

πŸ—οΈ Architecture

  • ListContainer
  • ListItem

🧠 Approach

  • Calculate visible indices
  • Render subset only

3. 🧾 Multi-step Form Wizard

πŸ“Œ Requirements

  • Step-based navigation
  • Validation per step
  • Save progress

βš™οΈ UI

  • Next/Prev buttons
  • Progress indicator

πŸ”„ State

  • Centralized form state

⚠️ Edge Cases

  • Back navigation retains data
  • Validation errors

πŸ—οΈ Architecture

  • Wizard
  • Step
  • Context for state

4. πŸ” Real-time Chat UI

πŸ“Œ Requirements

  • Message list
  • Auto-scroll
  • Typing indicator

βš™οΈ Behavior

  • New messages push bottom

⚠️ Edge Cases

  • Scroll position preservation
  • Duplicate messages

πŸš€ Performance

  • Virtualization for large chats

5. 🧠 Undo/Redo State Manager

πŸ“Œ Requirements

  • Maintain history
  • Undo/redo actions

πŸ”„ State

  • past, present, future

⚠️ Edge Cases

  • New action clears future

🧠 Approach

  • Stack-based state

6. πŸ“¦ Dynamic Dashboard Layout

πŸ“Œ Requirements

  • Drag & drop widgets
  • Resizable grid

⚠️ Edge Cases

  • Collision handling

πŸ—οΈ Architecture

  • Dashboard
  • Widget

7. πŸ” Role-based Component Rendering

πŸ“Œ Requirements

  • Render UI based on user roles

⚠️ Edge Cases

  • Unauthorized access

🧠 Approach

  • HOC or wrapper component

8. 🧾 Table with Sorting, Filtering, Pagination

πŸ“Œ Requirements

  • Multi-column sort
  • Server/client filtering

⚠️ Edge Cases

  • Large datasets

πŸš€ Performance

  • Memoized sorting

9. 🧠 Global Toast Notification System

πŸ“Œ Requirements

  • Show multiple toasts
  • Auto-dismiss

πŸ—οΈ Architecture

  • Context API

10. πŸ” File Explorer (Tree View)

πŸ“Œ Requirements

  • Nested folders
  • Expand/collapse

⚠️ Edge Cases

  • Deep nesting

11. 🧩 Modal Manager System

πŸ“Œ Requirements

  • Multiple modals
  • Stack management

12. πŸ“Š Real-time Stock Dashboard

πŸ“Œ Requirements

  • Live updates
  • Graph rendering

⚠️ Edge Cases

  • Rapid updates

13. 🧠 Form Builder (Drag & Drop)

πŸ“Œ Requirements

  • Build forms dynamically

14. πŸ” Polling + Manual Refresh System

πŸ“Œ Requirements

  • Auto refresh every X sec
  • Manual refresh

15. πŸ“¦ Shopping Cart with Optimistic Updates

πŸ“Œ Requirements

  • Instant UI update
  • Rollback on failure

16. 🧠 Tabs with Lazy Loading

πŸ“Œ Requirements

  • Load content on demand

17. πŸ” Search + Highlight System

πŸ“Œ Requirements

  • Highlight matches in large text

18. πŸ”„ Component Visibility Tracker

πŸ“Œ Requirements

  • Detect if component in viewport

πŸ“Œ What These Test

These problems simulate:
  • Real production UI systems
  • State architecture decisions
  • Performance bottlenecks
  • Component composition skills
  • Edge-case handling mindset

πŸš€ If You Want Next Level

Below is a FAANG-level interview set (20 questions) on React Components (Functional & Class Basics). These emphasize decision-making, internals, trade-offs, debugging, and performance awareness.

🧠 Senior React Interview Questions β€” Components


1. When would you intentionally choose a Class Component over a Functional Component today?

πŸ” Follow-up

  • How would you implement error boundaries using functional components?
  • What are the trade-offs?

βœ… Strong Answer

  • Primarily for Error Boundaries (until recently functional alternatives stabilized)
  • Legacy systems where refactoring cost is high
  • Class lifecycle sometimes clearer for debugging complex flows
class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {}
}

❌ Weak Answer

  • β€œClass components are faster” πŸ‘‰ Incorrect β€” no inherent performance advantage

2. Explain how React keeps track of state in functional components internally.

πŸ” Follow-up

  • Why does hook order matter?

βœ… Strong Answer

  • React stores hooks in a linked list tied to Fiber nodes
  • State is mapped by call order, not variable names

❌ Weak Answer

  • β€œReact tracks state by variable name” πŸ‘‰ Completely incorrect mental model

3. You see unnecessary re-renders in a deep component tree. How do you debug it?

πŸ” Follow-up

  • What tools and techniques do you use?

βœ… Strong Answer

  • Use React DevTools Profiler
  • Identify prop changes (reference vs value)
  • Check parent re-renders
  • Apply memoization strategically

❌ Weak Answer

  • β€œJust add React.memo everywhere” πŸ‘‰ Blind optimization β†’ can worsen performance

4. Why does this cause a bug?

setCount(count + 1);
setCount(count + 1);

πŸ” Follow-up

  • How does batching affect this?

βœ… Strong Answer

  • Both updates use stale value
  • React batches updates β†’ final state incorrect

❌ Weak Answer

  • β€œBecause setState is async” πŸ‘‰ Incomplete explanation

5. How would you design a reusable component system for a large application?

πŸ” Follow-up

  • How do you prevent tight coupling?

βœ… Strong Answer

  • Use composition over inheritance
  • Isolate concerns
  • Use controlled props + slots pattern

❌ Weak Answer

  • β€œJust break into smaller components” πŸ‘‰ Lacks architectural thinking

6. Explain a real-world bug caused by using index as key.

πŸ” Follow-up

  • When is it acceptable?

βœ… Strong Answer

  • Reordering lists β†’ incorrect DOM reuse
  • Example: form inputs shifting values

❌ Weak Answer

  • β€œIt’s only a performance issue” πŸ‘‰ It’s a correctness issue

7. How do closures impact React components?

πŸ” Follow-up

  • Give a real bug example

βœ… Strong Answer

  • Closures capture stale values
  • Common in async callbacks, effects

❌ Weak Answer

  • β€œClosures don’t matter in React” πŸ‘‰ Fundamental misunderstanding

8. What are the trade-offs of lifting state up?

πŸ” Follow-up

  • When does it become a problem?

βœ… Strong Answer

  • Enables shared state
  • But leads to prop drilling + unnecessary renders

❌ Weak Answer

  • β€œIt’s always best practice” πŸ‘‰ Not scalable in large apps

9. Why is React.memo sometimes ineffective?

πŸ” Follow-up

  • How do you fix it?

βœ… Strong Answer

  • Fails with unstable references (objects/functions)
<Child data={{ a: 1 }} />

❌ Weak Answer

  • β€œBecause memo is buggy” πŸ‘‰ Misunderstanding of reference equality

10. Explain reconciliation and its assumptions.

πŸ” Follow-up

  • How do keys affect it?

βœ… Strong Answer

  • React uses O(n) diffing heuristic
  • Assumes stable structure + keys

❌ Weak Answer

  • β€œReact compares everything deeply” πŸ‘‰ Incorrect

11. You have a component that fetches data. It sometimes shows outdated results. Why?

πŸ” Follow-up

  • How do you fix it?

βœ… Strong Answer

  • Race condition
  • Older request resolves after newer one

❌ Weak Answer

  • β€œAPI is slow” πŸ‘‰ Avoids root cause

12. How would you prevent unnecessary re-renders in a form-heavy UI?

πŸ” Follow-up

  • Controlled vs uncontrolled trade-offs?

βœ… Strong Answer

  • Split components
  • Use local state
  • Avoid global re-renders

❌ Weak Answer

  • β€œUse Redux” πŸ‘‰ Doesn’t solve rendering issue

13. Why are hooks restricted to top-level calls?

πŸ” Follow-up

  • What breaks if violated?

βœ… Strong Answer

  • Hook order consistency required for state mapping

❌ Weak Answer

  • β€œJust a React rule” πŸ‘‰ No understanding of internals

14. How do you handle expensive computations in components?

πŸ” Follow-up

  • When is useMemo harmful?

βœ… Strong Answer

  • Use useMemo when needed
  • Avoid overuse (adds overhead)

❌ Weak Answer

  • β€œAlways use useMemo” πŸ‘‰ Premature optimization

15. Describe a scenario where a component should NOT re-render but does.

πŸ” Follow-up

  • How do you fix it?

βœ… Strong Answer

  • Caused by new prop references
  • Fix via memoization or restructuring

16. What happens during render vs commit phases?

πŸ” Follow-up

  • Why is this important?

βœ… Strong Answer

  • Render = calculate changes (can be interrupted)
  • Commit = apply changes (synchronous)

17. How do you design components for scalability?

πŸ” Follow-up

  • What anti-patterns do you avoid?

βœ… Strong Answer

  • Small, composable components
  • Avoid monolith components

18. How would you debug a component that resets its state unexpectedly?

πŸ” Follow-up

  • What React concept is involved?

βœ… Strong Answer

  • Likely unmount/remount issue
  • Caused by conditional rendering or key change

19. Explain controlled vs uncontrolled components in a large system.

πŸ” Follow-up

  • When do you mix both?

βœ… Strong Answer

  • Controlled = predictable
  • Uncontrolled = performance-friendly

20. How do you decide component boundaries in a performance-critical app?

πŸ” Follow-up

  • What trade-offs do you consider?

βœ… Strong Answer

  • Balance between:
    • Reusability
    • Render isolation
    • Complexity

πŸ“Œ Final Evaluation Criteria (What Interviewers Look For)

A strong candidate demonstrates:
  • 🧠 Mental model of React internals
  • βš–οΈ Trade-off awareness
  • 🐞 Debugging mindset
  • πŸš€ Performance reasoning
  • πŸ—οΈ Component architecture thinking