useRef
React에서 DOM 요소나 값을 저장하고 변경하더라도 컴포넌트가 재렌더링되지 않도록 하는 훅
const ref = useRef(value)
console.log(ref) // {current:value]
useRef를 부르면 ref 오브젝트를 반환
const ref = useRef("hi")
console.log(ref) // {current:"hi"]
용도
1. 저장공간
State와 비슷하게 어떠한 값을 저장해주는 저장공간으로 사용
변경 시 렌더링을 발생시키지 말아야 하는 값을 다룰 때 유용( 불필요한 렌더링 방지 성능 최적화)
*State와 다른점
State 변화 -> 렌더링 -> 컴포넌트 내부 변수들 초기화
Ref 변화 -> 랜더링X -> 변수들 값 유지
∴ State 변화로 렌더링해도 Ref값 유지됨
사용
function App() {
const [state, setState] = useState(0);
const ref = useRef(0);
const statePlus = () =>{setState(state+1)}
const refPlus = () =>{ref.current += 1}
return(
<div>
<p>state : {state}</p>
<button onClick={statePlus}>state +1</button>
<p>ref : {ref.current}</p>
<button onClick={refPlus}>ref +1</button>
</div>
);
}
(결과)

-> ref 변화해도 랜더링X
변수와의 차이점은?
function App() {
const ref = useRef(0);
let vari = 0;
const stateVari = () =>{ vari += 1 }
const refPlus = () =>{ ref.current += 1 }
const [renderer, setRenderer] = useState(0);
const doRendering = () => {setRenderer(renderer + 1)};
return(
<div>
<p>ref : {ref.current}</p>
<button onClick={refPlus}>ref +1</button>
<p>vari : {vari}</p>
<button onClick={stateVari}>state +1</button>
<button onClick={doRendering}>렌더</button>
</div>
);
}
(결과)

-> ref와 다르게 변수는 0이 된다
why?
렌더링되면서
let vari = 0; 이 다시 실행되면서 0으로 초기화되게 때문!
2. DOM 요소에 접근
ref를 통해 돔 요소에 접근해 여러 가지 일 가능
ex) input 요소를 클릭하지 않아도 포커스를 주고 싶을 때
사용
const ref = useRef(); // ref 객체 생성, 초기값 null
<input ref={ref}/> //접근할 요소에 ref속성으로 연결, 해당 요소 ref.current에 할당
console.log(ref) // {current : <input>}
console.log(ref.current); // <input> 요소 직접 접근 가능
- input 요소를 클릭없이 포커스
function App() {
const inputRef = useRef();
useEffect(()=>{
inputRef.current.focus();
},[])
const onClick = () => {
alert(`안녕하세요. ${inputRef.current.value}`);
inputRef.current.focus();
}
return(
<div>
<input type="text" ref={inputRef} placeholder="Name"/>
<button onClick={onClick}>확인</button>
</div>
);
}
+
const inputRef = useRef<HTMLInputElement>(null);'React' 카테고리의 다른 글
| [React] React with Typescript (0) | 2024.12.05 |
|---|---|
| [React] 컴포넌트 최적화(1) : useMemo (0) | 2024.12.03 |
| [React] Styled-Components에서 애니메이션, 테마 (0) | 2024.11.28 |
| [React] Styled Components (0) | 2024.09.24 |
| [React] Navigation (0) | 2024.09.19 |