Advanced React Patterns: Compound Components & More


As React apps scale, you’ll want to structure components for greater reusability and composability. Here are some powerful React patterns:

Compound Components

The compound components pattern creates component APIs with shared context:

// Parent exposes context through 'Box' component
function Layout({children}) {
  return <Box>{children}</Box>
}

// Children access shared context via Box
function Profile() {
  return (
    <Layout>
      <Box p={2}>
        <h1>Jane Doe</h1>
      </Box>
    </Layout>
  );
}

This provides more flexible APIs than just props.

Render Props

With render props, components accept a function prop that returns a React element:

// Render prop component
function Mouse({ render }) {
  return render(mousePosition); 
}

// Usage
<Mouse
  render={position => (
    <h1>The mouse position is {position.x}, {position.y}</h1>
  )}
/>

This allows components to dynamically determine what should render.

Higher-Order Components

A higher-order component (HOC) wraps a component to enhance it:

// HOC that handles logic
function withAuth(Component) {
  return props => (
    <Component {...props} /> 
  );
}

// Enhanced component
function ProfilePage() {
  return <h1>Private Profile</h1>; 
}

export default withAuth(ProfilePage);

HOCs provide separation of concerns for component logic.

Summary

  • Compound components provide context through shared components
  • Render props allow components to determine rendering
  • HOCs enhance component logic by wrapping components

These patterns unlock powerful techniques for reusable, configurable React components.