I've been messing around with some code and I think I just realized something stupid. Using Immutable.js in React without Flux or Redux is a fool's errand.
toggleTask(task) {
const found = _.find(this.state.taskList, task => task.name === task);
found.isDone = !found.isCompleted;
const index = _.findIndex(this.state.taskList, task => task.name === task);
const temp = Immutable.fromJS(this.state.taskList);
temp.setIn([index, 'isDone'], found.isDone).toJS();
this.setState({ taskList: temp.toJS() });
}
So basically before I realized how much of a fool I was I was making an Immutable object, changed it using Immutable.js methods and then changed it back to an array. It's useless, because shallow compare should work without immutable objects.
shouldComponentUpdate(nextProps) {
return (this.props.name !== nextProps.name || this.props.priority !== nextProps.priority || this.props.isDone !== nextProps.isDone );
}
I've been using lodash methods, but since I am comparing the props individually and because they're primitives (primitives like strings and booleans can't be immutables anyways), I don't think it really matters and it would probably have worked even if I didn't use them.
toggleTask(task) {
const found = _.find(this.state.taskList, task => task.name === task);
found.isDone = !found.isDone;
this.setState({ taskList: this.state.taskList });
}
So am I wrong to say that Immutable.js in React is useless without Redux or Flux? Is there something I am not understanding correctly? I've watched examples and they didn't quite make sense to me since I've never used Flux or Redux.
Yes, you're actually on the right track. The reason why Immutable.js is more useful with Redux/Flux is because Immutable.js allows you to make inexpensive shallow comparisons with deeply-nested json objects. That's its main advantage. In your case, I suspect you have a simple todo application where your state is a list of simple arrays, in that case you don't get anything from using Immutable.js, because you can just compare the properties, which isn't expensive. You may not need it in a Redux application either, but in large project you may often have very big deeply nested json objects, in that case Immutable.js is extremely useful.