Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 87

Headless Component for Reusability

Recommended resources

Hello! Welcome back to our module on Advanced Component and TypeScript Patterns.

In our previous lesson, we dove deep into creating polymorphic components using discriminated unions and the as prop. You learned how to build components that are flexible in their rendering output while maintaining strict type safety. This was a major step in separating a component's markup from its definition.

Today, we're going to take that separation a step further. Our goal is to build a headless component to separate logic from presentation for maximum reusability. We will extract a component's state management and behavioral logic—its "head"—entirely from its visual representation—its "body." This pattern is a cornerstone of modern, reusable, and maintainable UI development.

What is a Headless Component?

A headless component is a component that provides logic and state but renders no UI of its own. It encapsulates all the complex behaviors (e.g., managing open/close state, handling keyboard navigation, fetching data) and gives you, the developer, complete control over the final look and feel.

This abstraction is incredibly powerful.

Headless UI Component as a React Hook
This diagram perfectly illustrates the concept. A traditional component bundles tags (markup), styles, and state logic. The headless pattern abstracts away the tags and styles, leaving only the state logic, which is often encapsulated in a custom React Hook.

The primary benefits of this pattern are:

  • Maximum Reusability: The same logic can power a dropdown, a modal, or an accordion in completely different parts of your application with entirely different designs.
  • Separation of Concerns: It creates a clean boundary between logic (the "how it works") and presentation (the "how it looks"), making your codebase easier to reason about and maintain.
  • Flexibility and Control: You are never locked into a specific HTML structure or set of CSS classes. You have total freedom to style and structure the component as you see fit.

The Core Pattern: Logic in a Custom Hook

The most common and idiomatic way to implement the headless component pattern in modern React is by using a custom hook. The hook manages all the state and exposes the necessary values and functions for the UI to use.

The article "Headless Component: a pattern for composing React UIs" from Martin Fowler's blog provides an excellent walkthrough of this pattern. We'll follow its useDropdown example.

Headless Component: a pattern for composing React UIs

This article provides a definitive guide to the headless component pattern. We'll focus on the section that refactors a traditional component into a custom hook.

Please read the introduction and the section 'Implementing Headless Component with a Custom Hook'. Focus on: The initial problem: A Dropdown component where state, event handlers, and rendering logic are all mixed together. The solution: How the useDropdown custom hook is created to encapsulate all the state (isOpen, selectedItem, etc.) and logic (keyboard handling). The result: A clean, simple Dropdown component that consumes the hook and is only responsible for rendering the UI.

Let's break down the transformation described in the article.

Before (Monolithic Component):

function MonolithicDropdown({ items }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  // ... more state for keyboard navigation ...

  const handleKeyDown = (event) => {
    // ... complex switch statement for ArrowUp, ArrowDown, Enter, Escape ...
  };

  return (
    <div onKeyDown={handleKeyDown}>
      <button onClick={() => setIsOpen(!isOpen)}>
        {selectedItem ? selectedItem.label : 'Select...'}
      </button>
      {isOpen && (
        <ul>
          {items.map(item => (
            <li key={item.id} onClick={() => setSelectedItem(item)}>
              {item.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Here, logic and presentation are tightly coupled. Changing the markup, like using a div instead of a button, risks breaking the logic.

After (Headless Pattern):
First, we create the "head"—the custom hook that contains all the logic.

// The "Head" - A custom hook
function useDropdown({ items }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  // ... more state and logic ...

  const handleKeyDown = (event) => { /* ... */ };
  const toggleDropdown = () => setIsOpen(!isOpen);
  
  // Expose state and functions to the UI
  return {
    isOpen,
    selectedItem,
    getItemProps: (item) => ({ /* props for each item */ }),
    getToggleButtonProps: () => ({ /* props for the toggle button */ }),
    // ... and so on
  };
}

Then, we create the "body"—a lean, presentational component that is only concerned with rendering.

// The "Body" - A presentational component
function Dropdown({ items }) {
  const { 
    isOpen, 
    selectedItem,
    getItemProps,
    getToggleButtonProps 
  } = useDropdown({ items }); // Consume the logic

  return (
    <div>
      <button {...getToggleButtonProps()}>
        {selectedItem ? selectedItem.label : 'Select...'}
      </button>
      {isOpen && (
        <ul>
          {items.map(item => (
            <li {...getItemProps({ item })}>
              {item.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

The separation is now crystal clear. The useDropdown hook could be reused to build a completely different-looking dropdown with <div>s and custom styling, without changing a single line of logic.


Building Headless Form Components: A Practical Example

A very common and powerful use case for headless components is to create a simpler, reusable API over a more complex library, such as a form management library. Let's see how to build a headless FormInput component that abstracts away the boilerplate of a library like react-hook-form.

The following video from Web Dev Simplified is a masterclass in this technique. We will focus on the specific section where he builds the reusable form components.

I Will Never Use Shadcn Form Components Again

This video demonstrates how to create a highly reusable set of form components. While it covers a lot of ground, we will focus on the core part where a headless abstraction is built.

Watch the segment from 30:42 to 40:22. This is a dense but incredibly valuable section. Pay close attention to: The Problem: The verbose boilerplate required by react-hook-form's <Controller> component for every single input. The Goal: To replace that entire block with a simple <FormInput name="..." label="..." control={...} />. The Abstraction: How he creates a FormBase component. This component is the key piece of the headless pattern here—it contains the <Controller>, the generic field layout, and the error message logic, but it uses children to render the actual input element (<input>, <textarea>, etc.). The Implementation: How FormInput is then built as a thin wrapper around FormBase, providing the specific <input> element as a child. The TypeScript: Notice the heavy use of generics and utility types to ensure the final components are fully type-safe. This directly builds on what you've learned in previous lessons.

The pattern shown in the video is a slightly different flavor of headless component. Instead of just a hook, it's a headless wrapper component (FormBase) that uses a render prop (children) to delegate the final rendering. The principle remains the same: separating the reusable logic (form state connection) from the specific presentation (the input element). This creates an incredibly clean and declarative API for building forms.

Test your understanding!

Imagine you need to build a simple useToggle headless hook. This hook will manage a boolean state (e.g., for a "show/hide" feature or an on/off switch).

What state and functions would you need to manage inside the useToggle hook, and what would you return from it to be consumed by a presentational component?

Show answer

A simple useToggle hook would look something like this:

import { useState, useCallback } from 'react';

// The headless hook
export function useToggle(initialState: boolean = false) {
  // 1. State: The core boolean value.
  const [isOn, setIsOn] = useState(initialState);

  // 2. Logic: A function to toggle the state.
  // Using useCallback to memoize the function is a good practice.
  const toggle = useCallback(() => setIsOn(prev => !prev), []);

  // 3. Return: Expose the state and the toggle function.
  return { isOn, toggle };
}

// --- Example Usage (Presentational Component) ---
function ToggleButton() {
  const { isOn, toggle } = useToggle();

  return (
    <button onClick={toggle}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}

The useToggle hook knows nothing about buttons or text. It only manages the toggling logic. The ToggleButton component knows nothing about state management; it just consumes the state and the function to render the UI.


Alternative Patterns and Real-World Libraries

While custom hooks are the dominant pattern, it's worth knowing that libraries sometimes use a Context-based approach. This is common in component kits that offer composable parts, like <Dropdown.Root>, <Dropdown.Trigger>, and <Dropdown.Menu>. Here, a Dropdown.Root component would use a hook internally and provide its state and logic down to its children via React Context.

Many popular, modern UI libraries are built on this "headless" philosophy. They provide the difficult logic for accessibility and state management, giving you full control over the styling.

To see this in action, let's look at one of the most popular headless libraries, Headless UI, which is often paired with the utility-first CSS framework Tailwind CSS.

Headless UI 1.0 is out! Building React and Vue Components with Tailwind CSS

This video from Lachlan Miller gives a great overview of Headless UI and demonstrates how to consume its pre-built headless components.

Watch from the beginning to 04:25. This will show you the 'consumer' side of headless components. Notice how the <Menu> component from Headless UI provides render props (like the open state) that you can use to apply your own classes and styles, giving you complete visual control.


Conclusion

You've now learned one of the most powerful and scalable patterns in React development. By separating a component's logic from its presentation, you can build UIs that are more flexible, reusable, and easier to maintain.

Key Takeaways:

  • A headless component encapsulates logic and state but renders no UI itself, giving the developer full control over presentation.
  • The most common implementation pattern is a custom React hook that returns the necessary state and handler functions.
  • This pattern is extremely effective for building your own reusable abstractions, such as simplifying the API of a complex third-party library (e.g., for forms).
  • Popular libraries like Headless UI, Radix, and TanStack Table are built on this principle, providing robust, accessible logic that you can style however you wish.

Preview of the Next Lesson:
We've pushed our component patterns to be incredibly flexible. To support these advanced patterns, we often need equally advanced TypeScript capabilities. In our next lesson, we'll dive into one of the most powerful features in TypeScript's type system: you'll learn to use conditional types in TypeScript to create advanced, dynamic prop types. This will unlock a new level of precision and dynamism in your type definitions.