• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

ref 관련 질문드립니다

20.08.18 17:29 작성 조회수 199

1

안녕하세요 강의 수강 중 궁금한 점이 생겨 질문드립니다

1. function useRef<T>(initialValue : T | null) : RefObject<T>;
2. function useRef<T>(initialValue : T ) : MutableRefObject<T>;
3. function useRef<T = undefined>() : MutableRefObject<T | undefined>;
setTimeout, useRef 타이핑 강의 끝부분에서
<T>를 <number | null> 을 줬습니다.
그러면 2번 꼴이 만들어지는 거를 확인할 수 있었는데요,
그럼, <number> 만 잇엇을때에도 똑같이 Mutable~ 로 인식할수잇다고 생각햇는데,
제가 어디를 놓친건지 알려주시면 감사하겟습니다

답변 2

·

답변을 작성해보세요.

4

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Note that useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

Usage note: if you need the result of useRef to be directly mutable, include | null in the type of the generic argument.

공식문서의 설명인데 좀 더 보충해보겠습니다.

useRef<number>(null)의 경우를 생각해봅시다.

T를 number로 잡으면 initialValue는 null이므로 2번이 될 수 없습니다. 그래서 1번 RefObject가 됩니다.

1번에서는 T가 number여도 initialValue는 number | null이라서 null이 될 수 있습니다.

number | null을 T로 잡고 initialValue에 null을 넣으면 initialValue인 null은 T에 부합합니다. (T === number | null이므로) 따라서 2번이 됩니다.

0

devsn님의 프로필

devsn

질문자

2020.08.19

답변 감사합니다