Posts [React] useState 사용시 제네릭을 사용하면 좋을 때
Post
Cancel

[React] useState 사용시 제네릭을 사용하면 좋을 때

Typescript를 적용한 React 프로젝트에서 useState 훅을 사용시 일반적으로 아래와 같이 제네릭을 사용하지 않아도 무방하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const onIncrease = () => setCount(count + 1);
  const onDecrease = () => setCount(count - 1);
  return (
    <div>
      <h1>{count}</h1>
      <div>
        <button onClick={onIncrease}>+1</button>
        <button onClick={onDecrease}>-1</button>
      </div>
    </div>
  );
}

export default Counter;

하지만, 상태가 null일 수도 있고 아닐 수도 있을 때 제네릭을 사용하면 좋다.

1
2
type Information = { name: string; description: string };
const [info, setInformation] = useState<Information | null>(null);

출처

This post is licensed under CC BY 4.0 by the author.

[React] React.FC의 사용 여부에 따른 차이점

[프론트엔드 개발환경의 이해와 실습] 외부 패키지 관리 방법