Web Devlopment/ReactJs
#11 useRef
키모형
2025. 3. 24. 13:59
반응형
Hook useRef을 사용하면 렌더링 간에 값을 유지할 수 있습니다.
업데이트 시 다시 렌더링을 발생시키지 않는 변경 가능한 값을 저장하는 데 사용할 수 있습니다.
DOM 요소에 직접 접근하는 데 사용할 수 있습니다.
const refContainer = useRef(initialValue);
Hook을 사용하여 애플리케이션이 몇 번 렌더링되는지 세어보려고 하면 useStateHook 자체가 다시 렌더링을 발생시키기 때문에 무한 루프에 빠지게 됩니다. 이를 방지하려면 useRefHook을 사용하면 됩니다.
import { useState, useEffect, useRef } from "react";
export default 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>Render Count: {count.current}</h1>
</>
);
}
애플리케이션 렌더링을 추적하는 데 사용됩니다 useRef.
useRef()단 하나의 항목만 반환합니다. .이라는 객체를 반환합니다 current.
초기화할 때 useRef초기값을 다음과 같이 설정합니다 useRef(0).
DOM 요소 접근하기
React에서는 ref요소에 속성을 추가해서 DOM에서 직접 접근할 수 있습니다.
useRef입력에 초점을 맞추는 데 사용 :
import { useRef } from "react";
export default function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
console.log(inputElement); // {current: input} 출력됨
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
상태 변경 추적
Hook useRef은 이전 상태 값을 추적하는 데에도 사용할 수 있습니다.
useRef는 렌더링 간에 값을 유지할 수 있기 때문입니다 .
import { useEffect, useRef, useState } from "react";
export default 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>
</>
);
}
위 예제는 useState , useEffect, 의 조합을 사용하여 useRef 이전 상태를 추적합니다.
입력 필드에 텍스트를 입력하여 업데이트될 때마다 현재 값이 useEffect업데이트됩니다 .useRefinputValue
반응형