본문 바로가기

3주차

[React] - 구조 분해 할당(feat. useState)

안녕하세요! Web YB 이윤지 입니다.

이번 3주차 리액트를 배우면서, useState가 상태 관리를 위해 사용된다는 건 알겠는데,

const [value, setValue] = useState(초기값);

왜? 이렇게 쓰일까? 하고 궁금해서 이번 아티클의 주제로 리액트의 구조 분해 할당 (feat. useState) 를 선택했습니다.ㅎㅎ

 

1. 구조 분해 할당?

구조 분해 할당 문법은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

 

쉽게 말해서 배열이나 객체를 쪼개서 필드 값을 변수에 담을 수 있다.

 

*배열 구조 분해

const fruits = ['apple', 'berry', 'banana'];
const [one, two, three] = fruits;
console.log(one, two, three); // 'apple', 'berry'. 'banana'

const age = [20, 25, 40];
const ['Lee', 'Kim', 'Park'] = age;
console.log('Kim', 'Lee', 'Park'); // 20, 25, 40
let Kim, Lee, Park;

[Kim, Lee, Park] = [20,25,40];
console.log(kim); // 20
console.log(Lee); //25
console.log(Park); //40

선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있다.

 

*객체 구조 분해

const apple = {
  type: 'fruit',
  color: 'red',
  shape: 'circle'
}

const { type, color, shape } = apple;
console.log(type, color, shape); // 'fruit', 'red', 'circle'

객체에서는 키(key)를 기준으로 값을 변수에 할당하는 객체 구조 분해를 사용할 수 있습니다.

 

 

* 리액트에서의 구조 분해 할당

- useState

function Login() {
  const [inputValue, setInputValue] = useState({
    email: '',
    password: '',
  });
  
  const { email, password } = inputValue;

  const handleInput = event => {
    const { name, value } = event.target;
    setInputValue({
      ...inputValue,
      [name]: value,
    });
  };
  
  return (
    <form className='loginInput'>
      <input name='email' value={email} onChange={handleInput} />
      <input name='password' value={password} onChange={handleInput} />
    </form>
  );
}

이 코드에서

 

const { email, password } = inputValue;

inputValue 객체에서 email 과 password 값을 구조 분해 할당을 사용해서 추출한다.

이렇게 하면 inputValue.email 을 할 필요 없이 email로 inputValue 상태에 접근할 수 있다!

 

 

이 구조 분해 할당이라는 것이 처음에는 감이 잘 잡히지 않았는데, 알아가다 보니 상태와 상태 업데이트 함수를 짧고 직관적으로 정의할 수 있어서 코드의 가독성을 높여주고, 후에 유지 보수 할 때도 도움을 준다고 합니다.

 

이번 3주차 과제에서도 이 구조 분해 할당을 어디에 어떻게 써야 할 지 생각해 볼 수 있었습니다!