Skip to main content

Command Palette

Search for a command to run...

Compound Components in React

Updated
2 min read
A

As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.

Expert-Level Explanation

Compound components in React are a pattern where a set of components work together to form a complete UI element while allowing the user to control their composition. This pattern provides more flexibility in terms of configuration and composition than a single monolithic component. Compound components share an implicit state and communicate with each other via React's Context API or by passing props down from parent to child.

Creative Explanation

Think of compound components, like building a custom computer. You have different parts (components) like the CPU, GPU, and RAM, which you can choose and assemble based on your needs. Each part works together to make the computer (the whole UI element), but you have the freedom to select and configure each part (component) to suit your specific requirements.

Practical Explanation with Code

An example of a compound component in React:

import React, { createContext, useContext } from 'react';

const TabContext = createContext();

const Tabs = ({ children }) => {
  const [activeTab, setActiveTab] = React.useState(0);

  return (
    <TabContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabContext.Provider>
  );
};

const Tab = ({ index, children }) => {
  const { activeTab } = useContext(TabContext);

  return activeTab === index ? children : null;
};

const TabList = ({ children }) => <div>{children}</div>;

const TabPanel = ({ children }) => <div>{children}</div>;

// Usage
<Tabs>
  <TabList>
    <Tab index={0}>Tab 1</Tab>
    <Tab index={1}>Tab 2</Tab>
  </TabList>
  <TabPanel>
    <div>Content for Tab 1</div>
  </TabPanel>
  <TabPanel>
    <div>Content for Tab 2</div>
  </TabPanel>
</Tabs>

Real-World Example

In a web-based music player, compound components can be used for the playback controls. The mainPlaybackControl component would manage the state, while individual components like PlayButton, PauseButton, and VolumeControl would interact with this state, allowing the user to control the playback and volume.

ReactJS Fundamentals for Interviews

Part 1 of 50

React Fundamentals for Interviews: Quick, concise guides covering essential ReactJS topics. Perfect for last-minute interview prep and mastering core concepts in a short time.