useRef
1
const refContainer = useRef(initialValue);
useRef는 전달된 인수(initialValue)로 초기화된 변경 가능한 ref 객체를 반환합니다. HTML 문서에서 Javascript를 이용해서 element를 제어했듯이 useRef를 통해서 React에서는 element를 제어할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
useRef는 element의 property를 변경하는 것이기에 리렌더링이 일어나지 않는다. 이것에 주의하자.
forwardRef
useRef의 한계는 바로 HTML Tag에서만 적용할 수 있다는 점이다. 그러면 사용자가 정의한 Component는 어떻게 property에 접근할 수 있을까? 그때 사용하는 것이 ForwardRef이다.
1
2
3
4
5
6
7
8
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
useRef를 사용하고 싶은 Component를 React.forwardRef로 감싸면 해당 Component의 property에 접근할 수 있다. 하지만, 코드를 보면 결국 Component가 받는 ref를 Component 안에 있는 element로 전달하는 것일 뿐이다.