본문 바로가기

React

[React] Rest operation VS Spread operation

리액트를 공부하다보면 아래오 같은 코드를 자주 접할 수 있을 것이다.

import React from 'react';
import './style.css';

const Button = ({ children, loading, ...props }) => (
    <button className="button" disabled={loading} {...props}>
        {loading ? 'loading...' : children}
    </button>
);

Button.defaultProps = {
    loading: false,
};

export default Button;

Button 이라는 컴포넌트를 만들고 props를 받아서 처리하고 있다.

 

우리가 주목해야 할 것은  . . . 이다. (이하, 닷닷닷)

 

정답부터 말하면,

첫 번째로 쓰인 ({ children, loading, ...props })  이곳에서 닷닷닷은 Rest operation 이고

두 번째로 쓰인 {...props} 는 Spread operation이다.

 

Rest operation은 남은 값들은 배열 또는 객체로 묶어준다.

const object = {
  a: "a",
  b: "b",
  c: () => console.log("c")
};
const { a, b, ...rest } = object;
console.log(a, b, rest);

위 코드의 값을 예상해보면, a 와 b는 가져왔고 나머지에 대해 닷닷닷을 하고 있다. 따라서 obejct에서 남아있는 값들을 하나의 객체로 묶어서 반환 할 것이다.

 

결과는 아래와 같다.

 

Spread operation은 객체나 배열을 분해시켜준다.

const A = {
  a: "a"
};

const B = {
  b: "b"
};

const ABC = {
  ...A,
  ...B,
  c: "c"
};

위 코드의 결과는 아래오 같다.

객체 A와 객체 B가 분해되어 ABC 객체로 들어갔음을 확인할 수 있다.

'React' 카테고리의 다른 글

[React] Styled Component로 Global Theme 다루기  (0) 2020.04.01
[React] Currying 과 HOC 에 대해서  (0) 2020.04.01