> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anujpandey.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Headless components

# 📘 Headless Components in React — Complete Theory Guide

***

## 1. 📌 Introduction

### 🔹 What are Headless Components?

**Headless components** are components that:

* Contain **logic and behavior**
* Do **NOT include UI or styling**

👉 They provide:

> Behavior without enforcing presentation

***

### 🔹 Simple Mental Model

```js id="h1" theme={null}
const { isOpen, toggle } = useDropdown();
```

You control UI:

```js id="h2" theme={null}
<button onClick={toggle}>Toggle</button>
{isOpen && <div>Menu</div>}
```

👉 Logic = headless
👉 UI = your responsibility

***

### 🔹 Why is it Important?

Traditional components:

* Combine logic + UI → tightly coupled

Headless components:

* Separate concerns:

  * Logic (state, behavior)
  * UI (markup, styling)

### Benefits:

* 🎨 Full design flexibility
* 🔁 Reusable logic
* 🧩 Better composability
* 📦 Framework/library friendly

***

### 🔹 When and Why Do We Use It?

Use headless components when:

* 🎯 You want reusable behavior without UI constraints
* 🎨 Design system needs flexibility
* 🔄 Same logic used across different UIs
* ⚙️ Building libraries (e.g., dropdowns, modals)

***

### 🔹 Real-World Use Cases

* Dropdown menus
* Modals
* Tooltips
* Comboboxes
* Tabs (logic layer)

***

## 2. ⚙️ Concepts / Internal Workings

***

### 🔹 1. Separation of Concerns

Headless pattern splits:

| Layer | Responsibility     |
| ----- | ------------------ |
| Logic | State, behavior    |
| UI    | Rendering, styling |

***

### 🔹 2. Implementation Styles

Headless components can be implemented as:

* Custom hooks (most common)
* Render props
* Compound components

***

### 🔹 3. Hook-Based Headless Logic

```js id="h3" theme={null}
function useToggle() {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => setIsOpen(o => !o);

  return { isOpen, toggle };
}
```

👉 UI is completely external

***

### 🔹 4. Internal Behavior

Headless components:

* Manage state internally
* Expose APIs (functions, values)
* Do not render UI (or render minimal structure)

***

### 🔹 5. Relationship with Other Patterns

| Pattern             | Relationship          |
| ------------------- | --------------------- |
| Custom Hooks        | Core implementation   |
| Compound Components | Often combined        |
| Render Props        | Alternative approach  |
| Provider Pattern    | Used for shared logic |

***

### 🔹 6. Control vs Flexibility

Headless components give:

* Maximum flexibility
* Minimal constraints

👉 Trade-off:

* More responsibility for developer

***

## 3. 🧪 Syntax & Examples

***

## 🔹 Example 1: Headless Dropdown (Hook-Based)

### Logic:

```js id="h4" theme={null}
function useDropdown() {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => setIsOpen(o => !o);
  const close = () => setIsOpen(false);

  return { isOpen, toggle, close };
}
```

***

### UI Usage:

```js id="h5" theme={null}
function Dropdown() {
  const { isOpen, toggle } = useDropdown();

  return (
    <>
      <button onClick={toggle}>Toggle</button>
      {isOpen && <div>Menu</div>}
    </>
  );
}
```

***

## 🔹 Example 2: Headless Modal

```js id="h6" theme={null}
function useModal() {
  const [isOpen, setIsOpen] = useState(false);

  return {
    isOpen,
    open: () => setIsOpen(true),
    close: () => setIsOpen(false)
  };
}
```

***

## 🔹 Example 3: Render Props Version

```js id="h7" theme={null}
function Toggle({ children }) {
  const [on, setOn] = useState(false);
  return children({ on, toggle: () => setOn(!on) });
}
```

Usage:

```js id="h8" theme={null}
<Toggle>
  {({ on, toggle }) => (
    <button onClick={toggle}>{on ? "ON" : "OFF"}</button>
  )}
</Toggle>
```

***

## 🔹 Example 4: Headless + Compound Components

```js id="h9" theme={null}
const Context = createContext();

function Dropdown({ children }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <Context.Provider value={{ isOpen, setIsOpen }}>
      {children}
    </Context.Provider>
  );
}

Dropdown.Trigger = function({ children }) {
  const { setIsOpen } = useContext(Context);
  return <button onClick={() => setIsOpen(o => !o)}>{children}</button>;
};

Dropdown.Menu = function({ children }) {
  const { isOpen } = useContext(Context);
  return isOpen ? <div>{children}</div> : null;
};
```

***

## 🔹 Example 5: Controlled Headless Component

```js id="h10" theme={null}
function useToggle({ value, onChange }) {
  const [internal, setInternal] = useState(false);

  const isControlled = value !== undefined;
  const state = isControlled ? value : internal;

  const toggle = () => {
    if (isControlled) onChange(!value);
    else setInternal(s => !s);
  };

  return { state, toggle };
}
```

***

## 4. ⚠️ Edge Cases / Common Mistakes

***

### 🔹 1. Over-Flexibility (Too Much Responsibility)

👉 Problem:

* Developer must handle everything (UI, accessibility)

### Fix:

* Provide sensible defaults

***

### 🔹 2. Accessibility Ignored

👉 Problem:

* Missing ARIA roles, keyboard support

### Fix:

* Include accessibility logic in headless layer

***

### 🔹 3. State Synchronization Issues

```js id="h11" theme={null}
const [state, setState] = useState(props.value);
```

👉 Problem:

* Doesn’t update when props change

### Fix:

* Handle controlled/uncontrolled properly

***

### 🔹 4. Event Handling Complexity

👉 Problem:

* Outside click detection
* Keyboard navigation

***

### 🔹 5. Re-render Issues

👉 Problem:

* Unstable callbacks or objects

***

### 🔹 6. Mixing UI with Logic

```js id="h12" theme={null}
return <button>Click</button>; // ❌ not headless
```

👉 Breaks headless principle

***

### 🔹 7. Poor API Design

👉 Problem:

* Hard-to-use hooks or props

***

## 5. ✅ Best Practices

***

### 🔹 1. Keep Logic Pure

✔ No UI assumptions
✔ Only behavior

***

### 🔹 2. Provide Clean API

```js id="h13" theme={null}
const { isOpen, toggle, close } = useDropdown();
```

👉 Easy to consume

***

### 🔹 3. Support Controlled + Uncontrolled

```js id="h14" theme={null}
const isControlled = value !== undefined;
```

***

### 🔹 4. Handle Accessibility in Logic

✔ Keyboard navigation
✔ ARIA attributes

***

### 🔹 5. Memoize Values

```js id="h15" theme={null}
const toggle = useCallback(() => {...}, []);
```

***

### 🔹 6. Combine with Other Patterns

* Provider → shared state
* Compound → structured UI

***

### 🔹 7. Avoid Over-Abstraction

👉 Don’t create headless component if:

* Logic is simple
* Used only once

***

### 🔹 8. Document API Clearly

Explain:

* Inputs
* Outputs
* Expected usage

***

### 🔹 9. Keep Hook Focused

❌ Bad:

```js id="h16" theme={null}
useEverything()
```

✔ Good:

```js id="h17" theme={null}
useDropdown()
useModal()
```

***

### 🔹 10. Optimize for Reusability

* Avoid hardcoded assumptions
* Keep logic generic

***

# 🧠 Final Mental Model

* Headless components = **logic layer**
* UI = consumer responsibility
* Goal = **maximum flexibility**

***

## 🔚 Key Insight

Headless components represent:

> **Separation of behavior from presentation**

***

👉 Widely used in:

* Design systems
* Component libraries (Headless UI, Radix UI)

***

# 🧠 Senior-Level Conceptual Questions — Headless Components (Deep Dive)

***

## 1. What fundamental architectural problem do headless components solve?

### ✅ Answer

Headless components solve **tight coupling between logic and presentation**.

### 🔴 Problem:

Traditional components:

```js theme={null}
<Button variant="primary" />
```

* UI and behavior are bundled
* Hard to customize deeply

### 🟢 Headless Solution:

```js theme={null}
const { isOpen, toggle } = useDropdown();
```

👉 You control rendering completely.

### 💡 Why:

* Enables **maximum flexibility**
* Separates **behavior from UI**

***

## 2. How do headless components work internally in React?

### ✅ Answer

They:

1. Manage state using hooks
2. Expose state + actions
3. Let consumer render UI

```js theme={null}
function useToggle() {
  const [on, setOn] = useState(false);
  return { on, toggle: () => setOn(o => !o) };
}
```

### 💡 Why:

React hooks allow logic reuse without enforcing structure.

***

## 3. Why are custom hooks the most common implementation for headless components?

### ✅ Answer

Hooks:

* Provide logic without UI
* Are composable
* Avoid wrapper components

### 🔁 Comparison:

| Approach     | Limitation            |
| ------------ | --------------------- |
| HOC          | Adds component layers |
| Render Props | Nested callbacks      |
| Hooks        | Clean, flat, reusable |

👉 Hooks are the most ergonomic solution

***

## 4. What are the trade-offs of headless components?

### ✅ Answer

| Advantage        | Trade-off             |
| ---------------- | --------------------- |
| Full flexibility | More responsibility   |
| Reusable logic   | More boilerplate      |
| Design freedom   | Requires UI expertise |

### 💡 Insight:

Headless components shift complexity:
👉 From library → developer

***

## 5. How do headless components differ from compound components?

### ✅ Answer

| Headless      | Compound              |
| ------------- | --------------------- |
| Logic-focused | Structure-focused     |
| No UI         | UI structure included |
| Hook-based    | Context-based         |

### 💡 Insight:

* Headless = behavior layer
* Compound = UI composition layer

👉 Often used together

***

## 6. What are common performance pitfalls in headless components?

### ✅ Answer

* Recreating functions/objects
* Unstable callbacks
* Excessive re-renders

```js theme={null}
const toggle = () => setOpen(!open); // ❌ new function
```

### 🟢 Fix:

```js theme={null}
const toggle = useCallback(() => setOpen(o => !o), []);
```

***

## 7. Why is accessibility a major concern in headless components?

### ✅ Answer

Headless components:

* Don’t control UI
* Must still enforce accessibility behavior

### 💡 Example:

* Keyboard navigation
* ARIA roles

👉 Without it → inaccessible UI

***

## 8. How do you design a headless component that supports controlled and uncontrolled usage?

### ✅ Answer

```js theme={null}
function useToggle({ value, onChange }) {
  const [internal, setInternal] = useState(false);

  const isControlled = value !== undefined;
  const state = isControlled ? value : internal;

  const toggle = () => {
    if (isControlled) onChange(!value);
    else setInternal(s => !s);
  };

  return { state, toggle };
}
```

### 💡 Why:

* Supports both internal and external state control

***

## 9. What are subtle bugs caused by stale closures in headless hooks?

### ✅ Answer

```js theme={null}
const increment = () => setCount(count + 1); // ❌
```

### 🔴 Problem:

* Uses stale state

### 🟢 Fix:

```js theme={null}
setCount(c => c + 1);
```

***

## 10. How would you design a scalable headless dropdown system?

### ✅ Answer

Should include:

* Open/close state
* Keyboard navigation
* Outside click handling
* Accessibility

### 💡 Architecture:

* Hook for logic
* Optional compound components for structure

***

## 11. When should you NOT use headless components?

### ✅ Answer

Avoid when:

* UI is simple
* Logic is minimal
* Component is not reused

👉 Over-abstraction increases complexity

***

## 12. How do headless components enable design systems?

### ✅ Answer

* Provide reusable logic
* Allow teams to build custom UI on top

👉 Example:

* Same dropdown logic → different UI themes

***

## 13. What are debugging challenges with headless components?

### ✅ Answer

* Logic and UI are separate
* Harder to trace flow

### 💡 Fix:

* Clear API
* Good naming
* DevTools usage

***

## 14. How do headless components interact with context?

### ✅ Answer

* Context can provide shared logic across components

```js theme={null}
const context = useContext(DropdownContext);
```

👉 Useful for multi-part systems

***

## 15. What is the biggest architectural advantage of headless components?

### ✅ Answer

👉 **Maximum flexibility without sacrificing reuse**

* Logic reused everywhere
* UI fully customizable

***

## 16. How do headless components compare to render props?

### ✅ Answer

| Headless Hooks | Render Props   |
| -------------- | -------------- |
| Cleaner        | Nested         |
| Composable     | Verbose        |
| Modern         | Legacy pattern |

***

## 17. How do you prevent over-engineering in headless components?

### ✅ Answer

* Keep API minimal
* Avoid unnecessary abstraction
* Build only when reuse is clear

***

## 18. What real-world scenarios benefit most from headless components?

### ✅ Answer

* Dropdowns
* Modals
* Tooltips
* Comboboxes
* Complex UI interactions

👉 These require:

* Shared logic
* Flexible UI

***

## 🔚 Final Insight

At senior level, headless components are about:

* **Separating logic from UI**
* **Designing flexible APIs**
* **Balancing abstraction vs usability**

***

👉 Strong engineers:

* Know when to use headless pattern
* Combine it with compound/context patterns
* Optimize performance and DX

***

# 🧠 Senior-Level MCQs — Headless Components (Deep Understanding)

***

## 1. What is the most subtle risk when using headless components extensively?

### Options:

A. Increased bundle size
B. Loss of UI flexibility
C. Shifting too much responsibility to consumers
D. Inability to reuse logic

### ✅ Correct Answer: **C**

### 💡 Explanation:

Headless components delegate UI responsibility entirely to the consumer, which can lead to:

* Inconsistent UI
* Accessibility issues
* Duplication of UI logic

### ❌ Why others are wrong:

* A: Not inherent
* B: Opposite of reality
* D: Logic reuse is their strength

***

## 2. Why are custom hooks considered the best fit for headless components?

### Options:

A. They render UI automatically
B. They avoid additional component layers
C. They enforce styling
D. They reduce state usage

### ✅ Correct Answer: **B**

### 💡 Explanation:

Hooks:

* Provide logic only
* Avoid wrapper components (unlike HOCs/render props)

### ❌ Why others are wrong:

* A: Hooks don’t render UI
* C: No styling involved
* D: State is still used

***

## 3. What happens if a headless hook returns unstable function references?

```js id="hm1" theme={null}
return { toggle: () => setOpen(!open) };
```

### Options:

A. No issue
B. Causes infinite loop
C. Breaks memoization in consumers
D. React throws error

### ✅ Correct Answer: **C**

### 💡 Explanation:

New function each render → breaks `React.memo` or `useEffect` dependencies.

***

## 4. What is the key difference between headless components and compound components?

### Options:

A. Headless components use hooks
B. Compound components include UI structure
C. Headless components cannot share state
D. Compound components don’t use context

### ✅ Correct Answer: **B**

### 💡 Explanation:

Compound components define UI structure; headless components don’t.

***

## 5. Why is accessibility often harder with headless components?

### Options:

A. React doesn’t support accessibility
B. No built-in keyboard/ARIA handling
C. Hooks cannot manage events
D. Browser limitations

### ✅ Correct Answer: **B**

### 💡 Explanation:

Since UI is not provided, accessibility must be implemented manually.

***

## 6. What is a major performance pitfall in headless hooks?

### Options:

A. Using hooks
B. Returning new objects/functions each render
C. Using state
D. Using JSX

### ✅ Correct Answer: **B**

### 💡 Explanation:

Unstable references → unnecessary re-renders.

***

## 7. What is the effect of mixing UI logic inside a headless hook?

```js id="hm2" theme={null}
return <button>Click</button>;
```

### Options:

A. Improves performance
B. Breaks headless abstraction
C. No impact
D. Required for hooks

### ✅ Correct Answer: **B**

***

## 8. Why is controlled/uncontrolled support important in headless components?

### Options:

A. Reduces code
B. Allows flexibility in state management
C. Improves performance
D. Required by React

### ✅ Correct Answer: **B**

***

## 9. What is the biggest trade-off of headless components?

### Options:

A. Less flexibility
B. Increased boilerplate for consumers
C. Slower rendering
D. Cannot use hooks

### ✅ Correct Answer: **B**

***

## 10. What happens if a headless hook depends on stale state?

```js id="hm3" theme={null}
const increment = () => setCount(count + 1);
```

### Options:

A. Infinite loop
B. Stale closure bug
C. Memory leak
D. Syntax error

### ✅ Correct Answer: **B**

***

## 11. What is the primary advantage of headless components in design systems?

### Options:

A. Faster rendering
B. Reusable logic across different UI implementations
C. Smaller bundle size
D. Automatic styling

### ✅ Correct Answer: **B**

***

## 12. Why can headless components cause inconsistent UI across teams?

### Options:

A. Hooks are unstable
B. UI is fully controlled by consumers
C. Context issues
D. React limitations

### ✅ Correct Answer: **B**

***

## 13. What is a subtle issue when using headless hooks with `useEffect`?

```js id="hm4" theme={null}
useEffect(() => {
  toggle();
}, [toggle]);
```

### Options:

A. Syntax error
B. Infinite loop due to unstable function reference
C. No issue
D. React ignores dependency

### ✅ Correct Answer: **B**

***

## 14. Why are headless components often combined with compound components?

### Options:

A. To reduce state
B. To provide structure along with logic
C. To improve performance
D. To avoid hooks

### ✅ Correct Answer: **B**

***

## 15. What is a real-world scenario where headless components are NOT ideal?

### Options:

A. Complex UI components
B. Reusable logic
C. Simple one-off components
D. Design systems

### ✅ Correct Answer: **C**

***

## 16. What happens when headless logic is too generic?

### Options:

A. Improves flexibility
B. Becomes harder to use and maintain
C. Improves performance
D. Reduces code

### ✅ Correct Answer: **B**

***

## 17. What is the effect of returning large objects from headless hooks?

### Options:

A. No issue
B. Increased memory usage only
C. Unnecessary re-renders due to reference changes
D. Syntax error

### ✅ Correct Answer: **C**

***

## 18. Why is API design critical in headless components?

### Options:

A. React requires it
B. Consumers depend entirely on exposed API
C. Improves performance
D. Reduces state

### ✅ Correct Answer: **B**

***

## 19. What is the biggest debugging challenge with headless components?

### Options:

A. Syntax errors
B. Separation of logic and UI
C. Hook rules
D. JSX complexity

### ✅ Correct Answer: **B**

***

# 🔚 Final Insight

These MCQs test:

* Separation of concerns
* Performance awareness
* API design thinking
* Real-world pitfalls

***

👉 Senior-level takeaway:
Headless components are powerful but:

* Shift responsibility to consumers
* Require careful API design
* Demand strong understanding of React internals

***

# 🧠 Headless Components — Real-World Coding Problems (Senior Level)

***

## 1. 🟡 Headless Toggle Hook

### 📌 Problem

Build a `useToggle` hook that manages boolean state.

### Constraints

* Support controlled + uncontrolled modes

### Expected Behavior

```js theme={null}
const { state, toggle } = useToggle();
```

### Edge Cases

* Controlled prop updates
* Prevent stale state

### 🪜 Solution Approach

1. Use `useState` for internal state
2. Detect controlled mode
3. Use functional updates

***

## 2. 🟡 Headless Dropdown Hook

### 📌 Problem

Create `useDropdown` managing open/close state.

### Constraints

* Support outside click closing

### Expected Behavior

```js theme={null}
const { isOpen, toggle, close } = useDropdown();
```

### Edge Cases

* Multiple dropdowns
* Event cleanup

### 🪜 Approach

1. Manage state
2. Attach `click` listener
3. Cleanup on unmount

***

## 3. 🟠 Headless Modal Hook

### 📌 Problem

Create `useModal` for opening/closing modal.

### Constraints

* Escape key support

### Edge Cases

* Multiple modals
* Focus handling

***

## 4. 🟠 Headless Tabs Logic

### 📌 Problem

Create `useTabs` hook managing active tab.

### Constraints

* Dynamic tabs

### Expected Behavior

```js theme={null}
const { activeId, setActiveId } = useTabs();
```

***

## 5. 🟠 Headless Accordion Logic

### 📌 Problem

Support single/multiple expand modes.

### Edge Cases

* Toggle same item
* Controlled mode

***

## 6. 🔴 Headless Combobox (Searchable Select)

### 📌 Problem

Build logic for searchable dropdown.

### Constraints

* Keyboard navigation

### Edge Cases

* Async search
* Debouncing

***

## 7. 🔴 Headless Tooltip System

### 📌 Problem

Create `useTooltip` with positioning logic.

### Constraints

* Hover + focus triggers

***

## 8. 🔴 Headless Form Validation Hook

### 📌 Problem

Build reusable validation logic.

### Constraints

* Sync + async validation

***

## 9. 🔴 Headless Pagination Logic

### 📌 Problem

Build `usePagination`.

### Constraints

* Dynamic page size

***

## 10. 🔴 Headless Infinite Scroll Hook

### 📌 Problem

Detect scroll near bottom.

### Constraints

* Throttle events

***

## 11. 🔴 Headless Drag-and-Drop Logic

### 📌 Problem

Manage drag state.

### Edge Cases

* Nested elements

***

## 12. 🔴 Headless Notification System

### 📌 Problem

Manage notification queue.

### Constraints

* Auto-dismiss

***

## 13. 🔴 Headless Keyboard Navigation System

### 📌 Problem

Handle arrow key navigation across items.

### Edge Cases

* Circular navigation

***

## 14. 🔴 Headless Multi-Select Logic

### 📌 Problem

Manage multiple selected items.

***

## 15. 🔴 Headless Tree View Logic

### 📌 Problem

Expand/collapse nested nodes.

***

## 16. 🔴 Headless Data Fetching Hook

### 📌 Problem

Build caching + loading logic.

### Edge Cases

* Race conditions

***

## 17. 🔴 Headless Undo/Redo System

### 📌 Problem

Track history of state changes.

***

## 18. 🔴 Headless Virtualization Logic

### 📌 Problem

Render only visible items.

***

## 19. 🔴 Headless Permission System

### 📌 Problem

Check access rules.

***

# 🔚 Final Insight

These problems test:

* Logic abstraction
* Hook design
* Edge-case handling
* Performance awareness

***

👉 Senior-level expectation:
You should:

* Design clean APIs
* Handle controlled/uncontrolled patterns
* Optimize re-renders
* Think in reusable logic systems

***

# 🛠️ Senior Code Review — Headless Components Debugging Challenges

***

## 1. ❗ Stale State in Toggle Hook

```js id="hb1" theme={null}
function useToggle() {
  const [on, setOn] = useState(false);

  const toggle = () => setOn(!on);

  return { on, toggle };
}
```

### 🔍 What’s wrong?

`toggle` uses stale `on` value.

### 💡 Why it happens

Closures capture old state → rapid calls lead to incorrect toggles.

### ✅ Fix

```js id="hb1fix" theme={null}
const toggle = () => setOn(prev => !prev);
```

### 🧠 Best Practice

Always use functional updates when exposing state setters.

***

## 2. ❗ Unstable Function Reference

```js id="hb2" theme={null}
return {
  toggle: () => setOpen(o => !o)
};
```

### 🔍 What’s wrong?

New function created every render.

### 💡 Why

Breaks memoization in consuming components.

### ✅ Fix

```js id="hb2fix" theme={null}
const toggle = useCallback(() => setOpen(o => !o), []);
return { toggle };
```

***

## 3. ❗ Missing Cleanup in Outside Click

```js id="hb3" theme={null}
useEffect(() => {
  document.addEventListener("click", handleClick);
}, []);
```

### 🔍 What’s wrong?

Event listener not removed.

### 💡 Why

Leads to memory leaks and duplicate handlers.

### ✅ Fix

```js id="hb3fix" theme={null}
useEffect(() => {
  document.addEventListener("click", handleClick);
  return () => document.removeEventListener("click", handleClick);
}, []);
```

***

## 4. ❗ Incorrect Controlled/Uncontrolled Logic

```js id="hb4" theme={null}
const [state, setState] = useState(props.value);
```

### 🔍 What’s wrong?

Doesn’t update when `props.value` changes.

### 💡 Why

`useState` runs only once.

### ✅ Fix

```js id="hb4fix" theme={null}
const isControlled = props.value !== undefined;
const state = isControlled ? props.value : internalState;
```

***

## 5. ❗ Infinite Loop in useEffect

```js id="hb5" theme={null}
useEffect(() => {
  toggle();
}, [toggle]);
```

### 🔍 What’s wrong?

`toggle` changes every render → infinite loop.

### 💡 Why

Function reference unstable.

### ✅ Fix

Memoize `toggle` or remove unnecessary effect.

***

## 6. ❗ Mixing UI Inside Headless Hook

```js id="hb6" theme={null}
function useModal() {
  return <div>Modal</div>;
}
```

### 🔍 What’s wrong?

Breaks headless principle.

### 💡 Why

Hook should return logic, not JSX.

### ✅ Fix

Return state + handlers only.

***

## 7. ❗ Missing Dependency in useCallback

```js id="hb7" theme={null}
const close = useCallback(() => setOpen(false), []);
```

### 🔍 What’s wrong?

May depend on stale state if logic grows.

### 💡 Why

Dependencies incomplete.

### ✅ Fix

Include dependencies or ensure safe usage.

***

## 8. ❗ Event Listener Using Stale State

```js id="hb8" theme={null}
useEffect(() => {
  function handleClick() {
    if (open) setOpen(false);
  }
  document.addEventListener("click", handleClick);
}, []);
```

### 🔍 What’s wrong?

`open` is stale inside handler.

### 💡 Why

Effect runs once → captures initial state.

### ✅ Fix

```js id="hb8fix" theme={null}
useEffect(() => {
  function handleClick() {
    setOpen(false);
  }
  document.addEventListener("click", handleClick);
  return () => document.removeEventListener("click", handleClick);
}, []);
```

***

## 9. ❗ Returning New Object Every Render

```js id="hb9" theme={null}
return { isOpen, toggle };
```

### 🔍 What’s wrong?

New object each render.

### 💡 Why

Breaks shallow comparison in consumers.

### ✅ Fix

```js id="hb9fix" theme={null}
return useMemo(() => ({ isOpen, toggle }), [isOpen, toggle]);
```

***

## 10. ❗ Over-Generic Hook

```js id="hb10" theme={null}
function useEverything() {
  // handles modal, dropdown, form
}
```

### 🔍 What’s wrong?

Too many responsibilities.

### 💡 Why

Hard to reuse, test, and maintain.

### ✅ Fix

Split into focused hooks.

***

## 11. ❗ Missing Ref for Outside Click

```js id="hb11" theme={null}
if (!event.target.closest(".dropdown")) {
  close();
}
```

### 🔍 What’s wrong?

Relies on DOM structure.

### 💡 Why

Breaks with dynamic markup.

### ✅ Fix

```js id="hb11fix" theme={null}
const ref = useRef();
if (ref.current && !ref.current.contains(event.target)) close();
```

***

## 12. ❗ Async Race Condition

```js id="hb12" theme={null}
useEffect(() => {
  fetchData().then(setData);
}, []);
```

### 🔍 What’s wrong?

Updates state after unmount.

### 💡 Why

No cleanup.

### ✅ Fix

```js id="hb12fix" theme={null}
useEffect(() => {
  let active = true;
  fetchData().then(d => active && setData(d));
  return () => { active = false };
}, []);
```

***

## 13. ❗ Re-render Storm from Large Hook Return

```js id="hb13" theme={null}
return { data, loading, error, actions, config };
```

### 🔍 What’s wrong?

Large object → frequent re-renders.

### 💡 Why

Any change affects entire object.

### ✅ Fix

Split or memoize parts.

***

## 14. ❗ Incorrect Keyboard Handling

```js id="hb14" theme={null}
if (e.key === "Enter") toggle();
```

### 🔍 What’s wrong?

Ignores accessibility patterns.

### 💡 Why

Missing other keys (Space, Arrow keys).

### ✅ Fix

Implement full keyboard support.

***

## 15. ❗ Missing Dependency in useEffect

```js id="hb15" theme={null}
useEffect(() => {
  if (isOpen) attachListeners();
}, []);
```

### 🔍 What’s wrong?

Doesn’t react to `isOpen` changes.

### 💡 Why

Dependency array incomplete.

### ✅ Fix

```js id="hb15fix" theme={null}
useEffect(() => {
  if (isOpen) attachListeners();
}, [isOpen]);
```

***

## 16. ❗ Derived State Inside Hook

```js id="hb16" theme={null}
const [filtered, setFiltered] = useState(items.filter(...));
```

### 🔍 What’s wrong?

Derived state stored unnecessarily.

### 💡 Why

Can go stale.

### ✅ Fix

Compute with `useMemo`.

***

## 17. ❗ Memory Leak from setTimeout

```js id="hb17" theme={null}
setTimeout(() => setOpen(false), 3000);
```

### 🔍 What’s wrong?

No cleanup.

### 💡 Why

Timeout runs after unmount.

### ✅ Fix

```js id="hb17fix" theme={null}
useEffect(() => {
  const id = setTimeout(...);
  return () => clearTimeout(id);
}, []);
```

***

## 18. ❗ Overusing Context in Headless Hook

```js id="hb18" theme={null}
const context = useContext(AppContext);
```

### 🔍 What’s wrong?

Couples hook to global state.

### 💡 Why

Breaks reusability.

### ✅ Fix

Keep hook independent.

***

## 🔚 Final Takeaway

These bugs highlight:

* ⚠️ Closure pitfalls
* ⚠️ Reference instability
* ⚠️ Event lifecycle issues
* ⚠️ Over-abstraction mistakes

***

👉 Senior-level expectation:
You should:

* Design stable APIs
* Prevent unnecessary re-renders
* Handle async and event lifecycles safely

***

# 🧠 Senior Frontend Architect — Headless Components Machine Coding Problems

***

## 1. 🔴 Headless Dropdown System (Accessible + Composable)

### 📌 Requirements

* Build a headless `useDropdown` + optional compound API
* Support:

  * Open/close
  * Keyboard navigation (↑ ↓ Enter Esc)
  * Outside click detection

### 🖥️ UI Behavior

* Trigger toggles menu
* Arrow keys move focus
* Enter selects item

### 🔄 State/Data Flow

* `isOpen`, `activeIndex`, `selectedItem`
* Exposed via hook

### ⚠️ Edge Cases

* Multiple dropdowns on page
* Nested dropdowns
* Rapid open/close

### ⚡ Performance

* Avoid global listeners per instance
* Memoize handlers

### 🏗️ Architecture

* Hook for logic
* Optional compound wrapper for structure

### 🪜 Approach

1. Manage open state
2. Track focused index
3. Add keyboard handlers
4. Handle outside click via `ref`

***

## 2. 🔴 Headless Combobox (Search + Async)

### 📌 Requirements

* Searchable dropdown with async data fetching

### 🖥️ UI Behavior

* Typing filters options
* Arrow navigation + selection

### 🔄 Data Flow

* `query`, `results`, `isLoading`

### ⚠️ Edge Cases

* Debounce input
* Race conditions

### ⚡ Performance

* Cache results
* Cancel stale requests

### 🪜 Approach

1. Manage input state
2. Debounce API calls
3. Handle keyboard navigation

***

## 3. 🔴 Headless Modal System with Focus Trap

### 📌 Requirements

* `useModal` hook
* Focus trap + escape key support

### 🖥️ UI Behavior

* Focus stays inside modal
* Escape closes

### ⚠️ Edge Cases

* Nested modals
* Restore focus on close

### ⚡ Performance

* Avoid re-renders of entire tree

***

## 4. 🔴 Headless Tabs (Dynamic + Lazy)

### 📌 Requirements

* Dynamic tabs with lazy-loaded panels

### 🖥️ UI Behavior

* Only active tab content rendered

### ⚠️ Edge Cases

* Rapid switching
* Tab removal

***

## 5. 🔴 Headless Tooltip Engine

### 📌 Requirements

* Position tooltip relative to trigger

### ⚠️ Edge Cases

* Viewport overflow
* Scroll reposition

### ⚡ Performance

* Use `requestAnimationFrame`

***

## 6. 🔴 Headless Form Engine (Validation + State)

### 📌 Requirements

* Manage form state + validation centrally

### 🔄 Data Flow

* Field-level subscriptions

### ⚠️ Edge Cases

* Async validation
* Nested fields

### ⚡ Performance

* Prevent full form re-renders

***

## 7. 🔴 Headless Infinite Scroll Hook

### 📌 Requirements

* Detect when user reaches bottom

### ⚠️ Edge Cases

* Fast scrolling
* API delays

### ⚡ Performance

* Throttle/debounce scroll

***

## 8. 🔴 Headless Drag-and-Drop System

### 📌 Requirements

* Manage drag state across components

### ⚠️ Edge Cases

* Nested drop zones
* Touch support

### ⚡ Performance

* Avoid excessive DOM updates

***

## 9. 🔴 Headless Multi-Select with Tags

### 📌 Requirements

* Select multiple items
* Show selected tags

### ⚠️ Edge Cases

* Duplicate selection
* Keyboard navigation

***

## 10. 🔴 Headless Tree View (Recursive)

### 📌 Requirements

* Expand/collapse hierarchical data

### ⚠️ Edge Cases

* Deep nesting
* Lazy loading nodes

***

## 11. 🔴 Headless Virtualized List

### 📌 Requirements

* Render large list efficiently

### ⚠️ Edge Cases

* Dynamic heights

### ⚡ Performance

* Windowing logic

***

## 12. 🔴 Headless Keyboard Navigation System

### 📌 Requirements

* Manage focus across list/grid

### ⚠️ Edge Cases

* Circular navigation
* Disabled items

***

## 13. 🔴 Headless Notification Queue

### 📌 Requirements

* Manage global notifications

### ⚠️ Edge Cases

* Burst notifications
* Auto-dismiss timing

***

## 14. 🔴 Headless Permission System

### 📌 Requirements

* Determine access rules

### ⚠️ Edge Cases

* Dynamic role updates

***

## 🔚 Final Insight

These problems simulate:

* UI logic abstraction
* Accessibility challenges
* Performance optimization
* Real-world component systems

***

👉 Senior-level expectations:

You should:

* Design **clean headless APIs**
* Handle **complex interaction logic**
* Optimize **re-renders and events**
* Ensure **accessibility + UX**

***

# 🧠 FAANG-Level Frontend Interview — Headless Components

***

## 1. When would you choose headless components over traditional UI components?

### 🔍 Follow-up:

* When is it over-engineering?
* What are the trade-offs?

### ✅ Strong Answer:

* Use when:

  * Logic needs to be reused across different UIs
  * Design flexibility is critical (design systems)
* Avoid when:

  * Component is simple or used once

👉 Trade-off:

* Flexibility vs increased responsibility & boilerplate

### ❌ Weak Answer:

> “When we want reusable code”

👉 Fails because:

* Too generic, no trade-off analysis

***

## 2. How do headless components work internally in React?

### 🔍 Follow-up:

* Why are hooks preferred?

### ✅ Strong Answer:

* Encapsulate logic using hooks
* Return state + actions
* UI handled externally

```js theme={null}
const { isOpen, toggle } = useDropdown();
```

👉 Hooks allow logic reuse without UI constraints

### ❌ Weak Answer:

> “They don’t have UI”

👉 Fails because:

* Doesn’t explain mechanism

***

## 3. What are the biggest performance pitfalls in headless components?

### 🔍 Follow-up:

* How do you optimize them?

### ✅ Strong Answer:

* Unstable references (functions/objects)
* Frequent state updates
* Large return objects

Fix:

* `useCallback`, `useMemo`
* Split logic

### ❌ Weak Answer:

> “Too many re-renders”

👉 Fails because:

* Lacks specifics

***

## 4. How do headless components differ from compound components?

### 🔍 Follow-up:

* Can they be combined?

### ✅ Strong Answer:

| Headless   | Compound      |
| ---------- | ------------- |
| Logic only | UI structure  |
| Hook-based | Context-based |

👉 Often combined:

* Headless logic + compound UI

### ❌ Weak Answer:

> “Both are reusable”

👉 Fails because:

* No distinction

***

## 5. Why is accessibility a critical challenge in headless components?

### 🔍 Follow-up:

* What should you handle?

### ✅ Strong Answer:

* No UI → must implement:

  * Keyboard navigation
  * ARIA roles
  * Focus management

👉 Missing these → inaccessible UI

### ❌ Weak Answer:

> “We add ARIA”

👉 Fails because:

* Too shallow

***

## 6. How would you design a scalable headless dropdown system?

### 🔍 Follow-up:

* What edge cases would you handle?

### ✅ Strong Answer:

* Manage:

  * Open/close state
  * Keyboard navigation
  * Outside click
* Handle:

  * Multiple instances
  * Nested dropdowns

***

## 7. What are common bugs caused by stale closures in headless hooks?

### 🔍 Follow-up:

* How do you fix them?

### ✅ Strong Answer:

```js theme={null}
setCount(count + 1); // ❌
```

Fix:

```js theme={null}
setCount(c => c + 1);
```

👉 Closures capture old state

***

## 8. How would you debug a headless component not behaving correctly?

### 🔍 Follow-up:

* What tools/strategies?

### ✅ Strong Answer:

1. Inspect hook state
2. Check dependencies
3. Verify event handlers
4. Use React DevTools

***

## 9. What is the biggest architectural advantage of headless components?

### 🔍 Follow-up:

* How does it help design systems?

### ✅ Strong Answer:

👉 Separation of logic and presentation

* Enables multiple UI implementations
* Promotes reuse

***

## 10. What are the trade-offs of headless components?

### 🔍 Follow-up:

* How do you mitigate them?

### ✅ Strong Answer:

* Pros:

  * Flexibility
  * Reusability
* Cons:

  * Boilerplate
  * Complexity
  * Accessibility burden

Mitigation:

* Good API design
* Documentation

***

## 11. How do you prevent over-abstraction in headless components?

### 🔍 Follow-up:

* What signals indicate overuse?

### ✅ Strong Answer:

* Avoid when:

  * Logic is simple
  * Not reused

👉 Over-abstraction → harder to maintain

***

## 12. How would you design controlled/uncontrolled behavior in headless hooks?

### 🔍 Follow-up:

* Why is this important?

### ✅ Strong Answer:

* Detect controlled mode
* Delegate state to parent if controlled

👉 Improves flexibility

***

## 13. What are subtle bugs when using headless hooks with useEffect?

### 🔍 Follow-up:

* Example?

### ✅ Strong Answer:

* Unstable dependencies → infinite loops

```js theme={null}
useEffect(() => {
  toggle();
}, [toggle]);
```

***

## 14. How do headless components interact with context?

### 🔍 Follow-up:

* When would you use both?

### ✅ Strong Answer:

* Context provides shared state
* Headless hook provides logic

👉 Used together for complex systems

***

## 15. What is a real-world scenario where headless components shine?

### 🔍 Follow-up:

* Why not use prebuilt UI?

### ✅ Strong Answer:

* Dropdowns, modals, comboboxes
* Need:

  * Custom UI
  * Reusable logic

***

## 16. How would you ensure good developer experience (DX) for headless APIs?

### 🔍 Follow-up:

* What makes a good API?

### ✅ Strong Answer:

* Clear naming
* Minimal surface area
* Predictable behavior

***

## 17. What happens if headless logic returns large objects?

### 🔍 Follow-up:

* How to fix?

### ✅ Strong Answer:

* Causes unnecessary re-renders
* Fix:

  * Memoization
  * Split logic

***

## 18. How do you handle event lifecycles in headless components?

### 🔍 Follow-up:

* What are common mistakes?

### ✅ Strong Answer:

* Add/remove listeners correctly
* Avoid stale closures

***

## 19. What is the biggest debugging challenge in headless components?

### 🔍 Follow-up:

* How do you overcome it?

### ✅ Strong Answer:

👉 Separation of logic and UI

* Hard to trace flow
* Solution:

  * Clear APIs
  * Logging
  * DevTools

***

# 🔚 Final Insight

At FAANG-level, headless components are evaluated as:

* A **logic abstraction pattern**
* A **design system building block**
* A **trade-off between flexibility and complexity**

***

👉 Strong candidates:

* Design **clean, minimal APIs**
* Handle **edge cases & accessibility**
* Optimize **performance and re-renders**

***
