HardComponent Patterns💻 Output Question

Compound components — shared context without props

💡

Hint

Compound components share state through context implicitly. Users compose them freely (<Tabs><Tab id='home'/></Tabs>) without managing the active state themselves.

What does this output?

// Simulates compound component pattern
function createTabs() {
  let activeTab = null;
  const state = { active: null };

  return {
    Root(defaultTab, render) {
      state.active = defaultTab;
      return render(state);
    },
    Tab(id, label) {
      return {
        id, label,
        isActive: () => state.active === id,
        activate: () => { state.active = id; }
      };
    },
  };
}

const Tabs = createTabs();

const tab1 = Tabs.Tab('home', 'Home');
const tab2 = Tabs.Tab('settings', 'Settings');

Tabs.Root('home', () => null); // set default

console.log(tab1.isActive()); // home is active
console.log(tab2.isActive());

tab2.activate();
console.log(tab1.isActive()); // home no longer active
console.log(tab2.isActive());

Correct Output

true
false
false
true

Why this output?

Explanation: Shared state.active acts like context. Both Tab instances read from the same state object. Activating tab2 changes state.active — tab1.isActive() now returns false.

Key Insight: Compound components share state through context implicitly. Users compose them freely () without managing the active state themselves.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz