본문 바로가기
Project/Rate My Resident

3. Spread Operator (Managing Array State)

by 빠니몽 2023. 3. 2.

2023.03.02

 

0. Background

The reason that made me search for and use it is basically that I wanted to manage a state of an array through useState hook. It didn't work when I tried just updating the array with array functions like this:

import {useState} from 'react';

const [tags, setTags] = useState([]);

const setTags = (tag) => {
	setTags(tags.push(tag));
};

const removeTags = () => {
	setTags(tags.pop(tag));
};

So, it was needed to fix and make it run in an intended way and I found out spread syntax.

1. Reason the previous code didn't work

According to official React docs, arrays are basically an object. Therefore, we should treat arrays in React state as read-only. We can't use arr[0] = 'bird', which is the re-assigning, and also we need to avoid using push() or pop() which are the methods that mutate the array. Instead, we can use other ways that React Docs suggests.

tags[0] = "cool";
setTags(tags.pop());
setTags(tags.push());

2. Alternatives

Use these methods:

/* When you wanna add an element */
setTags([...arr,element]);

/* When you wanna remove an element */
setTags(tags.filter(tag => if tag === element));

/* When you wanna replace an element */
setTags(tags.map(tag => ));