Dramatically simplify your React code

Manuel De Leon
2 min readSep 23, 2016

--

This is going to be a straightforward post. I’ll take the todos Redux example and rewrite it using ViewModel. At first I thought it wouldn’t make such a good example because hey, how complicated can it be? As it turns out you can make anything as complicated as you want it to be.

Just to be clear, this is not going to be an introduction to ViewModel. Only a taste of it.

Our little app looks like this:

It lets you add todo items to a list, strike the ones completed, and filter by active or completed. A few minor details are that you can’t add a blank todo, the input box is cleared after adding a todo, and the footer items change from a link to a span when you click on them.

Here’s the code with Redux:

And that’s it!

I’m only kidding, of course there’s more…

That is insane. The indirection and run around is staggering. You need to juggle a LOT of information in your head to know what’s going on. “Easy to reason about” it is not.

Now let’s rewrite that using ViewModel.

First stop is index.js which basically loads the App and a shared container (more on this in a bit).

Next we create a container (called ‘todoList’) with the state to share (todos list and the filter), a function that returns the filtered list, and it encapsulates the actions you can perform on it (add a todo item and toggle a todo item between active and completed). This is the bulk of our app.

The App component just displays the Header, TodoList, and Footer:

The Header puts the shared container in a property called ‘todoList’. It renders a form with an input and a button. The method ‘addTodo’ is called when you click the button or press enter on the input. ‘this.todoList.addTodo’ is essentially the ‘addTodo’ method on the shared container we created before (shared.js).

The TodoList uses the shared container the same way Header does. The list items are repeated for each object in ‘todoList.filtered’, it toggles the todo item when the li is clicked, and it takes care of the li’s style (strike-through or not).

Footer is pretty straightforward, it just displays the selection items, passing the filter and label:

The Selection component also uses the shared container and it updates the filter when the item is clicked.

And that’s it! No, this time I’m not kidding.

Check out the source code and documentation for more information.

Let me know if you have any questions. I’ll be happy to answer them.

--

--