How to use Immutable.js Records with React and Redux

Pierre Renaudin
Jun 8, 2016 · 2 min read

It’s the small things that change your product. React and Flux can be small things, but using them has changed our product like we could never imagined.

As we continue to improve our app, we struggled with the lack of consistency in our models, even if they were immutable. They were generic types (i.e. Map, Array), so we couldn’t precisely validated propTypes given to our components. 🌀

As Immutable.js was already in our project, we thought we could take advantage of the Immutable.Record to build our models to:

  • export a clear type for each model;
  • define model attributes;
  • expose getters if needed.

So, we can start be defining our first model, a Task record with default value and getters:

Alongside this model representing a unique task, we define another record to represent tasks list, TaskMap:

We could now make the most of these two records and refactor our Redux Reducer to ensure that our store state is a TaskMap with only Task records as values ( keys are Task ids):

Finally, we can create a container to present our data and connect it to our application state. We import the TaskMap model to validate our props:

And we do the same in our TaskListItem children to ensure that this component receives a Task model:

Now, if we mess up with the TaskListItem component, a clear message will pop up in our console. 👀

The message is clear enough to focus our attention on the wrong type given in the component container: it increases the component reusability and gives direct feedback if something in our app state is wrong. 👌

That’s all folks :) Easy to setup, great to use. We now have a consistent model representation for our data. Plus, the records are extendable and we can define on them… testing and debugging is easier now \o/ Next step could be defining types with Flow or Typescript… See you later!

Credit to Draft.js, a project maintained by Facebook, and from where great ideas can be taken about Immutable data structure, tests, code clarity…

Leave email, sticky notes behind. Start tracking your work with your team, clients and partners in Azendoo (https://www.azendoo.com).

Kudos to Antoine Hanriat and Emily Fiennes for reviewing this article 😘

Azendoo Team

Read all stories about teamwork, project collaboration &…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store