const ref = useRef(value);
ref 오브젝트는 다음과 같은 구조를 가진다
{ current : value }
예를 들어
const food = useRef(pizza);
food 라는 이름의 ref 오브젝트를 만들고 value 값으로 pizza라는 값을 넣었을 떄
{ current : pizza }
가 된다는 의미이다ref 오브젝트 안에 value를 변경하고 싶을 때는
ref.current = "변경할 값";
이렇게 변경 할 수 있다.
이렇게 반환된 ref 오브젝트는 컴포넌트가 계속 랜더링 되어도 컴포넌트가 언마운트 되기 전에는 값을 유지할 수 있다
useState를 사용해서 state를 변화 시키면 re-rendering이 되어서 컴포넌트 내부 변수들이 초기화 된다고 하였다.
그러나 ref는 값을 아무리 변경하여도 re-rendering이 발생하지 않아서 값이 유지된다는 특징이 있다.
또한 state가 변화해서 re-rendering이 발생하여도 ref의 값은 유지가 된다.
코드를 통해 알아보자
import React, { useState, useRef } from "react";
const App = () => {
const [count, setCount] = useState(0);
const countRef = useRef(0);
const increaseCountState = () => {
setCount(count + 1);
}
const increaseCountRef = () => {
countRef.current = countRef.current + 1;
}
return (
<p>state : { count }</p>
<p>Ref : { countRef.current }</p>
<button onClick={increaseCountState}>State 증가</button>
<button onClick={increaseCountRef}>Ref 증가</button>
)
}
여기서
console.log(countRef);
출력해보면 { current : 0 }
형식의 ref 오브젝트가 출력되는 것을 알 수 있다.
State 증가 버튼을 누르면 state가 변화하기 때문에 re-rendering이 일어나서
화면에 값이 바뀌는 것을 볼 수 있지만
Ref 증가 버튼을 누르면 countRef의 current 값은 증가를 하지만 화면이 re-rendering이 일어날 때까지 화면에서 변화가 없는 것을 알 수 있다.
대표적인 예를 들어보자
<input />
인풋 창에 클릭을 하지 않아도 focus가 되도록 하고 싶을 때 ref를 사용할 수 있다.
Document.querySelector()
랑 비슷하다<input autoFocus/>
그래도 ref 이용해서 Dom 요소에 접근하는 방법이 있다는 것을 알아야하니까
import React, { useEffect, useRef } from "react";
const App = () => {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
},[])
return (
<input type="text" ref={inputRef}/>
)
}
그냥 자동 포커싱을 구현하고 싶으면 autoFocus 를 쓰자