How “Controllable” React components maximize reusability

A deep dive into what really makes React components reusable

How many times have you tried using a component just to find out you could not manipulate its state?

How many times did the component just not work “out of the box”?

Stop pulling your hair out — we can do something about it!

In this article, I will show you how to increase your components reusability by managing your components data flow in a better way.

Photo by Riccardo Annandale on Unsplash

There are 3 different ways to manage your data flow:

The Uncontrolled way, where the component manages its own data. The Controlled way, where the parent manages the data. The Controllable way, where you get the best of both worlds!

Choosing the right way will have a tremendous effect on the component’s reusability.

FYI, all the examples are in React, but the discussion in this article is really about concepts pertaining to components data flow. Those concepts are easily applied to Vue.js or any other framework that support components.

Introducing Tabs

Our story is the story of Tabs:

The Tabs component, holds the Banana and Apple tabs

Clicking on any tab will change the active one, indicated by a style and content change.

Let’s write a simple markup for it:

So, how do you decide which tab is active?

The Uncontrolled Way

Uncontrolled is when the component manages its own data.

Let’s look on a simple input element:

<input/>

Typing in an input element

Typing text in the input will set the value of the element with that text. Changing value from the outside is possible only by a DOM manipulation, for example, by using React’s ref and accessing the element’s instance.

Applying the same approach to Tabs, we get this: