Course contentsShow
← React
Lesson 1172 of 2,39630. Composition: Inversion of ControlFree lesson

Real-World Example: Building useToggle with Prop Getter

Create a reusable toggle hook that returns getTogglerProps for maximum flexibility in what element consumers use.

Real-World Example: Building useToggle with Prop Getter

You'll learn how to build a flexible, reusable toggle hook that lets consumers attach toggle behavior to any element they choose.

The Complete Pattern in Action

Let's build a useToggle hook that demonstrates the prop getter pattern in a practical, real-world way. Instead of forcing consumers to use a specific button or element, we'll return a getTogglerProps function that bundles all necessary props.

Building the Hook

function useToggle(initialState = false) {
  const [isOn, setIsOn] = useState(initialState);

  const toggle = () => setIsOn(prev => !prev);

  // The prop getter: returns everything needed to make an element toggleable
  const getTogglerProps = (userProps = {}) => {
    return {
      'aria-pressed': isOn,
      onClick: (event) => {
        // Call user's onClick first if provided
        userProps.onClick?.(event);
        // Then our toggle logic
        toggle();
      },
      ...userProps, // Spread user props last to allow overrides
    };
  };

  return { isOn, toggle, getTogglerProps };
}

Maximum Consumer Flexibility

Now consumers can toggle with anything they want:

function App() {
  const { isOn, getTogglerProps } = useToggle();

  return (
    <div>
      {/* Use it on a button */}
      <button {...getTogglerProps()}>
        {isOn ? 'ON' : 'OFF'}
      </button>

      {/* Or on a div */}
      <div {...getTogglerProps({ className: 'toggle-box' })}>
        Click me
      </div>

      {/* Or with custom onClick too */}
      <span {...getTogglerProps({ onClick: () => console.log('Clicked!') })}>
        Toggle
      </span>
    </div>
  );
}

The prop getter bundles accessibility, event handlers, and allows custom props—all while keeping your hook clean and your consumers flexible.

Key Takeaway: Prop getters give consumers full control over what element they use while your hook controls how it behaves—the perfect balance of flexibility and reusability.