...

/

The Controllable Pattern

The Controllable Pattern

Learn how to implement controllable behavior in higher-order components.

We'll cover the following...

Components in React are commonly described as controlled or uncontrolled with respect to some variable. If that variable is passed down to it through props, the component is controlled. If that variable is managed as state, the component is uncontrolled.

In its original incarnation, Carousel was uncontrolled with respect to slideIndex. With the HasIndex refactoring, the core of Carousel is now controlled, but the version of Carousel that this library’s users will consume is still uncontrolled. Nothing outside of Carousel can modify its slideIndex because that variable is kept in state.

Suppose you removed the HasIndex wrapper to make Carousel controlled. That would make the component more versatile since the user could change the slideIndex freely. But it would also make it more cumbersome since the user would have to implement their own slideIndexDecrement and slideIndexIncrement handlers.

What if you could get the best of both worlds? That’s what the controllable ...