useRef Hook을 사용하면 렌더 간에 값을 유지할 수 있다.
업데이트할 때 다시 렌더링하지 않는 변경 가능한 값을 저장하는데 사용할 수 있다.
DOM 요소에 직접 액세스하는 데 사용할 수 있다.
Hook을 사용하여 애플리케이션이 몇 번 렌더링 되는지 계산하려고 하면 useState Hook 자체가 다시 렌더링을 일으키기 때문에 무한루프에 빠지게 된다.
이를 피하기 위해 useRef Hook을 사용할 수 있다.
import { useState, useEffect, useRef } from 'react'
function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
})
return (
<>
<input
type = "text"
value = {inputValue}
onChange = {(e) => setInputValue(e.target.value)}
/>
<h1>{count.current}</h1>
</>
)
}
초기화 useRef할 때 초기 값을 설정한다. useRef(0)
일반적으로 React가 모든 DOM 조작을 처리하도록 하고 싶지만 useRef 문제를 일으키지 않고 사용할 수 있는 경우가 있다. React에서는 ref요소 속성을 추가하여 DOM에서 직접 접근할 수 있다.
import { useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Hook은 useRef 이전 상태 값을 추적하는 데에도 사용할 수 있다.
useRef는 렌더링 간에 값을 유지할 수 있기 때문이다.
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
useState, useEffect, 및 조합을 사용하여 useRef의 이전 상태를 추적 할 수 있다.
예제에서 입력 필드에 텍스트를 입력하여 업데이트 될 때마다 현재 값 useEffect을 업데이트하고 있다.