Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to convert Immutable.js Map to Object inside of react component

I am using redux and Immutable.js in my application, I added Immutable to the app a few weeks after I started developing the project and as I didn't want to change my current components to the Immutable's .get() syntax I converted the Immutable Maps in my store to Objects before using them inside of my components. Ex.:

@connect((store) => {
  return {
    login: store.login.toObject(),
    user: store.user.toObject()
  };
})

Is it a bad practice?Would that be relevant for the performance of my app?

like image 256
Bezzi Avatar asked Mar 11 '23 01:03

Bezzi


2 Answers

Yes, this is a VERY bad practice. In order for Immutable to convert your Immutable maps to JavaScript it has to walk the entire object; this is going to be slow. Also, you are losing a huge amount of the actual value of using ImmutableJS with React and Redux. Specifically, you now can no longer short circuit needless re-renders with a simple implementation of shouldComponentUpdate.

like image 72
rooftop Avatar answered Mar 13 '23 14:03

rooftop


If you want to use ImmutableJS Maps, but don't want to have to use get syntax, you can use Records. They have all the functionality of Maps, except for arbitrary-value keys (which accessor syntax wouldn't work on anyways).

A brief example:

// Specify the allowed fields and their default values
const TodoListState = Immutable.Record({ todos: undefined, filter: undefined })

// Instantiate the record using `new` and an object with the desired KV mapping
const initialTodoState = new TodoListState({ 
  todos: Immutable.List(),
  filter: undefined, // this is already the default, but I prefer being explicit
})

const initialTodos = initialTodoState.todos // List()
like image 27
Nicholas Montaño Avatar answered Mar 13 '23 15:03

Nicholas Montaño