React

[React] 함수형 컴포넌트에서 defaultProps와 default parameters 중 무엇을 사용해야 할까?

무하지 2022. 4. 3. 18:12
반응형

아래와 같이 defaultProps를 사용해서 props가 명시되지 않은 경우 기본값을 사용하게 할 수 있다

const Component = ({ prop1, prop2 }) => (
  <div></div>
);

Component.defaultProps = {
  prop1: 'hello',
  prop2: 'world',
};

 

ES6 문법에서, 아래와 같이 비구조화 할당을 이용해 default parameter를 지정해줄 수 있다.

const Component = ({ prop1='hello', prop2='world' }) => (
  <div></div>
);

 

위 두 방법 모두 동일한 기능을 수행하는데, 두 번째 방법(default parameter)을 사용하는 걸 추천한다.

 

defaultProps는 본래 클래스형 컴포넌트에서 사용되기 위해 만들어졌다.

 

함수형 컴포넌트에서는 곧 사라지게 될(deprecated) 기능이므로 최신문법인 아래 방법을 사용하는 게 좋다.

 

https://stackoverflow.com/questions/47774695/react-functional-component-default-props-vs-default-parameters

 

React functional component default props vs default parameters

In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameters on the function definition, examples: Default prop...

stackoverflow.com

 

+

그럴 일이 있으면 안되지만, defaultProps와 default parameters를 동시에 지정해주면 defaultProps가 우선순위를 갖는다.

반응형