KeepLearning
KeepLearning

Reputation: 377

React assinging array vaiable, which one is the best?

So, currently, in React, I want to update an array. Which option is the best?

I have the following:

const [users, setUsers] = useState(['1','2','3']);

Now, I want to filter out 3, and only having 1 & 2 in the array.

users.filter(item => item.name !== 3)

Which option is the best:

Option 1, copy array to a new variable:

const tempUsers = {... users.filter(item => item.name !== 3)}
setUsers(tempArray);

Option 2:

setUsers(users.filter(item => item.name !== 3))

Which one is better, and why we choose one over another?

Upvotes: 0

Views: 33

Answers (2)

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

this is a matter of code smell as said by Martin fowler in the book Refactoring.

the second option is better because it is more natural to read and you dont need the extra temp variable replace temp with query

Upvotes: 0

wentjun
wentjun

Reputation: 42556

Option 2,

setUsers(users.filter(item => item.name !== 3))

Would be sufficient.

This is because Array.filter() won't directly mutating state, since it creates a new array. Thus there is no need to take the additional step the spread the result into a new array before setting it to state.

Upvotes: 1

Related Questions