Todor Popov
Todor Popov

Reputation: 181

The best way to remove a key from react component's state

I am using a react class component, which holds a state, with (lets say..) a lot of key-value pairs stored into it. Upon user action (button press/toggle), I need to REMOVE / ADD a new key-value pair to the component's state. Adding one is relatively easy, but pulling out a key-value pair from the state can be done in several different ways, so I was wondering which one is best, most readable, most performant and most preferred by the ReactJS audience..

1) Option 1:

onRemove = key => {
    const newState = this.state;
    delete newState[key] // Interacts directly with the state, which might not be a good practice, or expended behaviour?
    this.setState(newState);
}

2) Option 2:

onRemove = key => {
    const {[key]: removedKey, ...newState} = this.state; // Defines two new variables, one of which won't be used - "removedKey";
    this.setState(newState);
}

There might be more ways to do it, and I am wondering which might be the best one, that can be used in any circumstance, no matter how 'big' the state gets...

Please share your thoughts based on your work experience with React & State management!

Thanks!

Upvotes: 2

Views: 1776

Answers (2)

Nick
Nick

Reputation: 16576

When I do something like this, I generally do a modified version of your "Option 1." As you currently have it, Option 1 mutates the state object, which you shouldn't do. Instead, create a shallow copy of state and then delete the key.

onRemove = key => {
    const newState = {...this.state};
    delete newState[key];
    this.setState(newState);
}

The reason I like this way over your Option 2 is subjective--It's very readable to me. Make a copy, delete a key. Simple and to the point.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074355

Option 1 isn't an option. You can't directly modify state in React.

Option 2 is fairly standard practice.

A third (to my mind lesser) option is to remove the property after cloning the object, but deleting properties from objects isn't what JavaScript engines optimize for, so I don't see any advantage to it over Option 2.

Upvotes: 0

Related Questions