DeployU
Interviews / Frontend Engineering / This component is not reusable. Refactor it using the composition pattern.

Questions

This component is not reusable. Refactor it using the composition pattern.

architecture Component Patterns Interactive Quiz Code Examples

A junior developer has created a Dashboard component. Inside, they’ve hardcoded three different types of panels: a WelcomePanel, a ChartPanel, and a SettingsPanel.

The code is very repetitive. Each panel has the same border, title styling, and padding, but the content inside is different. This makes the component hard to maintain and the panel styling is not reusable anywhere else.

Your task is to refactor this Dashboard component. Create a single, reusable Panel component that uses React’s composition pattern (specifically the children prop) to render different content inside.

The final UI should look identical, but the code should be much cleaner, more modular, and follow the “Don’t Repeat Yourself” (DRY) principle.

Dashboard - Refactor Using Composition
Your Code
import React from 'react';

// The styles for the panels are defined here for clarity.
const panelStyles = {
  border: '1px solid #ccc',
  borderRadius: '8px',
  padding: '16px',
  marginBottom: '16px',
  boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
};

const titleStyles = {
  margin: '0 0 10px 0',
  borderBottom: '1px solid #eee',
  paddingBottom: '10px',
};

// The anti-pattern: A monolithic component with repeated structure.
export default function Dashboard() {
  return (
    <div>
      {/* Welcome Panel */}
      <div style={panelStyles}>
        <h2 style={titleStyles}>Welcome</h2>
        <p>Welcome to your dashboard, Admin!</p>
      </div>

      {/* Chart Panel */}
      <div style={panelStyles}>
        <h2 style={titleStyles}>Analytics</h2>
        <p>Here are your user engagement charts.</p>
        <img src="https://via.placeholder.com/300x100.png?text=Chart" alt="Chart" />
      </div>

      {/* Settings Panel */}
      <div style={panelStyles}>
        <h2 style={titleStyles}>Settings</h2>
        <p>Configure your notification preferences.</p>
        <button>Edit Settings</button>
      </div>
    </div>
  );
}
// Validate the refactor
const code = document.querySelector('[data-editor]').textContent;

// Check for Panel component
if (!code.includes('Panel')) {
  throw new Error('Test failed: Create a reusable Panel component.');
}

// Check that Panel uses children prop
if (!code.match(/Panel[\s\S]*?children/)) {
  throw new Error('Test failed: Panel component should accept and render the children prop.');
}

// Check that Panel uses title prop
if (!code.match(/Panel[\s\S]*?title/)) {
  throw new Error('Test failed: Panel component should accept a title prop.');
}

// Check that Dashboard uses Panel component at least 3 times
const panelMatches = code.match(/<Panel/g);
if (!panelMatches || panelMatches.length < 3) {
  throw new Error('Test failed: Dashboard should use the Panel component for all three panels.');
}

// Check that repeated div structure is removed
const divMatches = code.match(/<div style={panelStyles}>/g);
if (divMatches && divMatches.length > 1) {
  throw new Error('Test failed: Remove repeated div structures. The Panel component should encapsulate this.');
}

// Success!
console.log('✓ All tests passed! Dashboard refactored using composition pattern.');
console.log('✓ Panel component is now reusable across the application.');
Click "Run Code" to see output...
Click "Run Code" to see test results...
How Different Experience Levels Approach This
Junior Engineer
Surface Level

I would extract the panel styling into a CSS class and apply it to each div, which would reduce some duplication.

Senior Engineer
Production Ready

I would create a reusable `Panel` component that accepts a `title` prop and uses `children` to compose its content. This leverages React's composition pattern, making the Panel independently reusable and testable. The Dashboard then becomes declarative, using `<Panel title='...'>content</Panel>` for each section, eliminating structural duplication while maintaining flexibility.

The original code violates the DRY (Don’t Repeat Yourself) principle. The container div with its style={panelStyles} and the h2 title are repeated for every panel. This is a classic sign that a component should be extracted.

The best way to fix this is by creating a generic Panel component that encapsulates the repeated structure and styling. We can then use props.children to place any content we want inside this panel. This is a core React concept called composition. The Panel component “contains” the children you pass to it.

This makes our Dashboard component much cleaner and gives us a Panel component we can reuse anywhere in our application.

Here is the corrected implementation:

import React from 'react';

const panelStyles = {
  border: '1px solid #ccc',
  borderRadius: '8px',
  padding: '16px',
  marginBottom: '16px',
  boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
};

const titleStyles = {
  margin: '0 0 10px 0',
  borderBottom: '1px solid #eee',
  paddingBottom: '10px',
};

// The reusable Panel component using composition
function Panel({ title, children }) {
  return (
    <div style={panelStyles}>
      <h2 style={titleStyles}>{title}</h2>
      {children}
    </div>
  );
}

// The refactored Dashboard, now clean and declarative
export default function Dashboard() {
  return (
    <div>
      <Panel title="Welcome">
        <p>Welcome to your dashboard, Admin!</p>
      </Panel>

      <Panel title="Analytics">
        <p>Here are your user engagement charts.</p>
        <img src="https://via.placeholder.com/300x100.png?text=Chart" alt="Chart" />
      </Panel>

      <Panel title="Settings">
        <p>Configure your notification preferences.</p>
        <button>Edit Settings</button>
      </Panel>
    </div>
  );
}
What Makes the Difference?
  • Context over facts: Explains when and why, not just what
  • Real examples: Provides specific use cases from production experience
  • Trade-offs: Acknowledges pros, cons, and decision factors

Practice Question

What is the primary advantage of using the composition pattern over inheritance in React?