Jin의 개발 블로그

React 에서 Array로 된 State 관리하기 본문

React

React 에서 Array로 된 State 관리하기

Youngjin Kwak 2023. 9. 23. 11:19

Introduction

React에서 Array로 된 State를 관리하는 방법 (추가, 변경, 삭제)에 대해 포스팅해볼 것 입니다. 예제는 React 18 버전과 Typescript로 되어 있습니다.

시작하기에 앞서 아래의 Array를 중점으로 사용할 것 입니다.

interface Person {
	id: number
    name: string
}

const [people, setPeople] = React.useState<Person[]>(
  Array.from({length: 3}, (_, i) => ({
    id: i + 1,
    name: `Test: #${i + 1}`,
  }))
)

React의 State는 Immutability 특성을 지니고 있기 때문에 Array의 몇몇 method를 활용하는 것이 쉽지 않습니다. 따라서 다른 방법을 사용해야합니다.

추가

앞에 추가

일반 Array의 경우 Array의 `unshift` method를 사용하면 쉽게 Array에 넣을 수 있었으나, React에서는 쉽지않습니다. Destructuring Assignment 방식을 이용하여 이를 해결 할 수 있습니다.

setPeople([
  {
    id: people.length + 1,
    name: 'John'
  },
  ...people,
])

맨 뒤에 추가

위에 설명한 것과 마찬가지로  `push` method를 사용하기 어렵기 때문에 Destructuring Assignment 방식을 사용합니다.

setPeople([
  ...people,
  {
    id: people.length + 1,
    name: 'John'
  },
])

특정 Index에 추가

특정 Index에 넣기위해서는 위에서 언급한 Destructing 방식과 Array의 `slice` method를 사용합니다.

const index = 2
setPeople([
  ...people.slice(0, index),
  {
  id: people.length + 1,
  name: 'John'
  },
  ...people.slice(index),
])

예제는 index가 2인 부분에 신규 데이터를 넣습니다.

 

`push()` 혹은 `pop()`과 같은 Method를 사용하고 싶을 때에는 Deep copy 방식을 사용하여 해결 할 수 있습니다.

const newPeople = [...people]
newPeople.push({
    id: people.length + 1,
    name: 'John'
})
setPeople(newPeople)

업데이트

맨앞의 데이터 업데이트

const newPeople = [...people]
newPeople[0] = {
	id: newPeople[0].id,
	name: 'New name #' + newPeople[0].id,
} 
setPeople(newPeople)

우선 Destructuring Assignment 을 이용하여 Array를 Deep copy하여 사용합니다. 그런 다음 index 0의 데이터를 재할당해줍니다. 맨뒤에 넣는 방법과 특정 index의 데이터를 업데이트도 같은 방식을 합니다.

특정 Index로 업데이트

const index = 2
const newPeople = [...people]
newPeople[index] = {
	id: newPeople[index].id,
	name: 'New name #' + newPeople[index].id,
} 
setPeople(newPeople)

위에서 사용한 방법과 똑같이 하면 됩니다. 다만 "0" 대신 특정 index를 넣는 것이 좀 다릅니다.

특정 조건으로 여러개 한번에 업데이트

Array의 `map()` method를 이용하여 특정 조건의 모든 데이터를 업데이트 할 수 있습니다.

setPeople(people.map(personEl => {
if(personEl.id % 2 === 0) {
  return {
    ...personEl,
    name: `Even - ${personEl.name}`
  }
}

return personEl
}))

 

위의 코드는 id의 값이 짝수인 데이터의 Name property를 변경하는 예제입니다.

삭제

맨 앞의 데이터삭제

const newPeople = [...people]
newPeople.shift()
setPeople(newPeople)

Deep copy 후 Array의 `shift()` method를 사용하여 쉽게 삭제할 수 있습니다. 마찬가지로 맨 뒤의 데이터를 삭제 할 때는 `pop()` method를 사용 하면 됩니다.

const newPeople = [...people]
newPeople.pop()
setPeople(newPeople)

특정 조건으로 여러개 한 번에 삭제

Array의 `filter()` method를 이용하여 특정 조건의 모든 데이터를 업데이트 할 수 있습니다.

setPeople(people.filter(personEl => personEl.id % 2 === 0))

위의 코드는 id가 짝수인 데이터만 남기고 나머지는 삭제하는 예제입니다.

Reference

https://stackoverflow.com/questions/36326612/how-to-delete-an-item-from-state-array

 

How to delete an item from state array?

The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left. people = ["Bob", "Sally", "Jack"] I now need to remove,...

stackoverflow.com

https://www.freecodecamp.org/news/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5/

 

Handling State in React: Four Immutable Approaches to Consider

by Cory House Perhaps the most common point of confusion in React today: state. Imagine you have a form for editing a user. It’s common to create a single change handler to handle changes to all form fields. It may look something like this: updateState(e

www.freecodecamp.org