Skip to content

Instantly share code, notes, and snippets.

@kylpo

kylpo/blog.md Secret

Created June 20, 2017 15:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kylpo/52182ffa76075352bc80a51a729cd3d1 to your computer and use it in GitHub Desktop.

A Naming Convention for Null Components

A component that returns null, and likely uses lifecycle hooks to make side effects, is a "Null Component".

https://gist.github.com/a8ee152fe5e319d3339cc6ae0b93845d

(I got the name from this oooold issue: facebook/react#1058)

Can You Spot Them?

Can you tell me which of these components renders nothing?

https://gist.github.com/d75a88f3988b13b9e67ff2eb450ef6c1

I can't either. I'd need prior knowledge of the components or read through how they were implemented.

If you are familiar with React Router V4, you may know that it doesn't render anything, but what if you could know without prior knowledge?

Introducing the <_NullComponent_ /> Convention

Aligning closely with the <Injector_ > naming convention, Null Components are denoted with a postfix AND prefix _. e.g. <_NullComponent_ />. The idea is that the additional prefix _ of a Null Component denotes that it is even more incomplete than an Injector.

Null Components are denoted with a prefix and postfix _. e.g. <_NullComponent_ />

Let's look at our example again with the naming convention applied. Which component(s) render nothing?

https://gist.github.com/b763b99358e3589ba32d59263804d28e

<_Redirect_ /> jumps out as a Null Component. I don't need to read its source or have prior knowledge of it's implementation to know this.

How about one more example, with an Injector Component added. How many components are rendered to the DOM?

https://gist.github.com/d90e21f8380f0b56a3ce98951cdb764f

By convention, we know that Style_ and _Redirect_ do not add anything to the DOM. So, we can mentally comment them out:

https://gist.github.com/6e14e197900379744f2842662d27633d

I count 2 in the above code.

It Gets Better

Can you spot the error(s) in this render?

https://gist.github.com/c93581f28426bc64c8b323e9252048c2

Yes! Null Components should never have children - they'd never be rendered.

Even Better with Tooling

Naming conventions enable tooling. I've edited my vim color scheme to style Null Components similarly to comments, which further reinforces their concept, and allows me to easily skim renders and identify or ignore them.

In the future, we might also have an editor with a toggleable option to hide all components that do not add to the DOM directly.

more conventions => more helpful tooling

Other naming conventions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment