useRef
- 랜더링과 관련 없이 동일한 참조를 유지
- useRef의 current 값이 변경되어도 리렌더링이 발생하지 않음
- setTimeout, setInterval 의 id, 외부 라이브러리를 사용해 생성된 인스턴스 등
- 화면 스크롤바의 위치 등
import { useState, useRef } from 'react';
import Timer from './Component/Timer';
const App = () => {
const [count, setCount] = useState(0);
const countRef = useRef(0);
const handleCountUp = () => {
setCount(count + 1);
}
const handleCountRefUp = () => {
countRef.current = countRef.current + 1;
console.log(countRef);
}
return (
<div>
<p>count: {count}</p>
<p>countRef: {countRef.current}</p>
<button onClick={handleCountUp}>count Up</button>
<button onClick={handleCountRefUp}>countRef Up</button>
</div>
)
};
export default App;
import { useState, useRef } from 'react';
import Timer from './Component/Timer';
const App = () => {
const [renderCount, setRenderCount] = useState(0);
let countVar = 0;
const countRef = useRef(0);
const handleCountVarUp = () => {
countVar = countVar + 1;
console.log("countVar: ", countVar);
};
const handleCountRefUp = () => {
countRef.current = countRef.current + 1;
console.log("countRef: ", countRef);
};
const handleRender = () => {
setRenderCount(renderCount + 1);
};
return (
<div>
<p>countVar: {countVar}</p>
<p>countRef: {countRef.current}</p>
<button onClick={handleCountVarUp}>countVar Up</button>
<button onClick={handleCountRefUp}>countRef Up</button>
<button onClick={handleRender}>Render</button>
</div>
)
};
export default App;
import { useRef, useEffect } from 'react';
import Timer from './Component/Timer';
const App = () => {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
const handleLogin = () => {
alert(`Hi, ${inputRef.current.value}`);
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type='text' placeholder='username'></input>
<button onClick={handleLogin}>login</button>
</div>
)
};
export default App;