3

Whenever a React class has a state object that is or contains an array, updating that state feels awkward. Usually what I do is

var newArrayThing = _.clone(this.state.arrayThing); //or slice()
newArrayThing[123] = 42; //update stuff
this.setState({arrayThing: newArrayThing});

Is there a better or more elegant way of handling this I am missing? Especially since I always feel this is unnecessary slow if the array is big and the change is small. All that copying for a simple change. But the state should not be edited directly seems to be the mantra.

The Facebook docs mention the Immutability Helpers, but they seem even more far fetched than this.

1 Answer 1

5

That is a very idiomatic way to do it but if you have concerns over cloning large arrays, you should definitely look into the update helper that you mentioned, it's not really that bad:

this.setState({
  arrayThing: React.addons.update(this.state.arrayThing, {123: {$set: 42}})
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.