Skip to main content

Search

Search problems, hooks, and pages

Accordion Component

Build an accordion where sections expand/collapse on click. Implement both single-open mode (only one section open at a time) and multi-open mode (multiple sections can be open simultaneously).

Requirements

  • Render a list of items, each with a header and collapsible body
  • Click a header to expand/collapse its body
  • Single-open mode: opening one section collapses any previously open section
  • Multi-open mode: any number of sections can be open at once
  • Toggle between single-open and multi-open modes at runtime
  • Smooth open/close animation

Key Patterns

openIndex: number | null (single-open)openItems: Set<number> (multi-open)CSS max-height transitionMUI Collapse componentToggle pattern with Set

Important

Interview Tip

For single-open: store openIndex (number|null). Clicking an open item sets it to null; clicking a closed item sets it to that index. For multi-open: store a Set<number>. Toggle = if Set has index, delete it; else add it. Spread into a new Set to trigger re-render: setOpen(new Set(prev).add/delete).
What is React?

React is a JavaScript library for building user interfaces. It was developed by Facebook and is now maintained by Meta and the open-source community. React uses a declarative paradigm and a virtual DOM to efficiently update the UI.

What is the Virtual DOM?

The Virtual DOM is a lightweight JavaScript representation of the real DOM. When state changes, React creates a new Virtual DOM tree, compares it with the previous one (diffing), and applies only the minimal set of changes to the real DOM (reconciliation).

What are React Hooks?

Hooks are functions that let you use React state and lifecycle features in function components. Common hooks: useState (state), useEffect (side effects), useRef (mutable refs/DOM access), useMemo/useCallback (memoization), useContext (context access).

What is the difference between useMemo and useCallback?

useMemo memoizes the RESULT of a function call. useCallback memoizes the FUNCTION ITSELF. Use useMemo for expensive computations, useCallback to prevent child re-renders when passing stable function references as props.

What is prop drilling and how do you avoid it?

Prop drilling is passing props through multiple levels of components that don't need them. Solutions: React Context API, Zustand/Redux for global state, component composition, or render props pattern.