ffxsam ffxsam - 5 months ago 35
React JSX Question

Deeply updating React state (array) without Immutable, any disadvantages?

I know using Immutable is a great way to deeply update React state, but I was wondering if there are any drawbacks I'm not seeing with this approach:


has the shape
{ userId: String, role: String }

If the user changes a user's role, the following method is executed:

changeMemberRole = (userId, event, key, value) => {
const memberIndex = _findIndex(this.state.members,
(member) => member.userId === userId);

if (memberIndex >= 0) {
const newMembers = [...this.state.members];

newMembers[memberIndex].role = value;
this.setState({ members: newMembers });

Would there be any advantage to replacing this with Immutable's
, other than potentially more terse syntax?


From the setIn docs:

Returns a new Map having set value at this keyPath. If any keys in keyPath do not exist, a new immutable Map will be created at that key.

This is probably not what you are looking for since you may not want to insert a new member with the given role if it does not exist already. This comes down to whether you are able to control the userId argument passed in the function and verify whether it exists beforehand.

This solution is fine. You can replace it with update instead, if you want to.