React Anti-Pattern: Overloaded

John Tucker
codeburst
Published in
2 min readNov 14, 2018

--

Sometimes it takes learning what not to do to learn what to do.

This article is also available in a video format.

The examples from this article are available for download.

The Anti-Pattern

In this simplified example, we have an application consisting of three features:

  • A function that outputs content to the console (submit feature)
  • A form consisting of two fields and a submit button (form feature)
  • A Swap Colors button swaps the background and foreground colors of the application’s title (color management feature)

The three features’ and a view’s interdependencies can be visualized as:

Our first implementation is to put all of the elements into a single file:

Observations:

  • Using the withColors higher-order component, this file defines two separate components, OverloadedBadWrapped and the exported OverloadedBad
  • The Formik (a third-party forms library) component, using the render props pattern, uses two in-line defined functions for it’s onSubmit (submit feature) and render (view) properties
  • While this simplified example is around seventy-five lines, a more realistic implementation likely would be several hundred lines

The problem here is that, this single file is both long and implements multiple features (it is overloaded); this is going to be a challenge when troubleshooting later.

A Better Way

While it takes a bit more effort up-front, breaking the application into multiple files (each with a focused responsibility) will make troubleshooting easier later.

The most lengthy file, the view, is a simple stateless presentational component with no functionality.

We inject the color management feature into the view using the withColors higher-order component (exports another component). I follow the hard-rule, however trivial, of only having one component per file.

Likewise we inject the form feature (passing transparently through the color management feature component) into the view with a stateless component (that is declarative in nature).

Finally, we implement the submit feature in a fourth component.

Next Steps

If you found this article helpful, I would encourage you to follow me as I am actively writing more like it.

--

--