Yanis Blogs JavaScript and Ruby. And Vim. And side-projects.

React without “this”

R

For some weird reason, even though React is rather functional in its philosophy (compare higher-order components and higher-order functions), they decided to use classes for components with a state. I want to stress it — the heavy classes usage in React is a mere API choice. There is nothing about React or its core values that couldn’t be represented with pure functions.

But classes add up to complexity (think inheritance vs. composition problem, overuse of complex hierarchies, over-engineering, etc.). You also have to deal with,this which eventually turns into some trash heap. Everyone assigns something to it, and then read hoping that the fragile state is still in a good shape.

Functional React components

In one of my side projects I’ve come up with a stupid solution, which abstracts away the OOP nature of components. I call it stupid because it adds a layer on top of React, while someone smarter could obviously simply rewrite React itself. Anyway, it works so perfectly for me, that I want to share.

First, let’s look at how it’s being used. And this is the most important part, because my goal here is to show that this is convenient for an end user. The implementation is not important (but we’ll talk about it later as well).

So, here’s a typical example.

You can see that there are no classes. The render function receives an object which we can call “context” with props, state and the setState function. Every callback function is described right there within the render function itself so they also have access to that object.

Then the lifecycle functions like willMount also receive that context object, so they can read from the state and then can update the state by using setState.

To actually create a stateful React component I use the function creatively called nothis.

Not bad, huh?

So what?

What I especially like about this approach:

  • Without "this" the code is much easier to read and comprehend. It is more JavaScript-ish in a good way…
  • No "this" also means, there’s no need to bind functions. Since every callback function is right here within the render method, it receives everything it needs.
  • We don’t have to explicitly set the state. We can simply use default values for function params.
  • I’ve found while rewriting my components, that the total count of code lines went down by around 20%.

Bonus: Implementation

Now let’s see at how "nothis" function can be implemented. Again, it was not the point of this article, and can be probably done much better. Still, here’s how I do it.

Not too gracious. But it works.

Let me know

That’s it. If you find this approach interesting, or you think this why this might be not a good idea please contact me via twitter. I’m looking forward to hear more opinions on this.

Yanis Blogs JavaScript and Ruby. And Vim. And side-projects.

Recent Posts

Categories

Meta