기본 : useState<타입>(값)
// state의 타입을 명시해서
const [like, setLike] = useState<boolean>(false);
//로직 생략
setLike (!like);
기본값만 null일 때
// 유니온 타입으로 전달
const [like, setLike] = useState<boolean | null>(null);
//생략
if (like) {
// 좋아요 true 일 때만 실행할 로직
}
객체가 포함된 객체일 때
// state 타입 정의
interface Comment {
comment: string;
username: string;
date: string;
star: number;
}
//생략
const [comments, setComments] = useState<Comment[]>([]);
setComments(...comments, {
comment: '넘 맛있어요..',
username: 'kim',
date: '2020.07.01',
star: 4
}, {
comment: '가성비 최고!',
username: 'lee',
date: '2020.07.20',
star: 5
})
const reviewRef = useRef<HTMLDivElement>(null); // 1
//로직 생략
return (
<>
<Review reviewTextRef={reviewRef} /> // 2
<div ref={reviewRef}> // 3
리뷰
</div>
</>
)