๋ ๋๋ง ์ค์ ์ฝ๊ธฐ/์ฐ๊ธฐ๋ฅผ ํ์ง ์๋ ref์ ์ฌ๋ฐ๋ฅธ ์ฌ์ฉ๋ฒ์ ๊ฒ์ฆํฉ๋๋ค. useRef() ์ฌ์ฉ๋ฒ์ โ์ฃผ์ํ์ธ์!โ ์น์
์ ์ฐธ๊ณ ํ์ธ์.
๊ท์น ์ธ๋ถ ์ฌํญ
Ref๋ ๋ ๋๋ง์ ์ฌ์ฉ๋์ง ์๋ ๊ฐ์ ๋ณด์ ํฉ๋๋ค. State์ ๋ฌ๋ฆฌ ref๋ฅผ ๋ณ๊ฒฝํด๋ ์ฌ๋ ๋๋ง์ด ํธ๋ฆฌ๊ฑฐ๋์ง ์์ต๋๋ค. ๋ ๋๋ง ์ค์ ref.current๋ฅผ ์ฝ๊ฑฐ๋ ์ฐ๋ ๊ฒ์ React์ ์์์ ๊นจ๋จ๋ฆฝ๋๋ค. Ref๋ ์ฝ์ผ๋ ค๊ณ ํ ๋ ์ด๊ธฐํ๋์ง ์์์ ์ ์์ผ๋ฉฐ, ๊ทธ ๊ฐ์ ์ค๋๋์๊ฑฐ๋ ์ผ๊ด๋์ง ์์ ์ ์์ต๋๋ค.
Ref ๊ฐ์ง ๋ฐฉ๋ฒ
๋ฆฐํธ๋ ref๋ก ์๊ณ ์๋ ๊ฐ์๋ง ์ด๋ฌํ ๊ท์น์ ์ ์ฉํฉ๋๋ค. ๊ฐ์ ์ปดํ์ผ๋ฌ๊ฐ ๋ค์ ํจํด ์ค ํ๋๋ฅผ ๋ฐ๊ฒฌํ๋ฉด ref๋ก ์ถ๋ก ๋ฉ๋๋ค.
-
useRef()๋๋React.createRef()์์ ๋ฐํ๋ ๊ฐconst scrollRef = useRef(null); -
ref๋ก ๋ช ๋ช ๋๊ฑฐ๋Ref๋ก ๋๋๋ ์๋ณ์๊ฐ.current๋ฅผ ์ฝ๊ฑฐ๋ ์ฐ๋ ๊ฒฝ์ฐbuttonRef.current = node; -
JSX
refprop์ ํตํด ์ ๋ฌ๋ ๊ฒฝ์ฐ (์:<div ref={someRef} />)<input ref={inputRef} />
๋ฌด์ธ๊ฐ๊ฐ ref๋ก ํ์๋๋ฉด ๊ทธ ์ถ๋ก ์ ํ ๋น, ๊ตฌ์กฐ ๋ถํด ๋๋ ํฌํผ ํธ์ถ์ ํตํด ๊ฐ์ ๋ฐ๋ผ๊ฐ๋๋ค. ์ด๋ฅผ ํตํด ref๊ฐ ์ธ์๋ก ์ ๋ฌ๋ ๋ค๋ฅธ ํจ์ ๋ด๋ถ์์ ref.current์ ์ก์ธ์คํ๋ ๊ฒฝ์ฐ์๋ ๋ฆฐํธ๊ฐ ์๋ฐ ์ฌํญ์ ์ฐพ์๋ผ ์ ์์ต๋๋ค.
์ผ๋ฐ์ ์ธ ์๋ฐ ์ฌ๋ก
- ๋ ๋๋ง ์ค์
ref.current์ฝ๊ธฐ - ๋ ๋๋ง ์ค์
refs์ ๋ฐ์ดํธ - State์ฌ์ผ ํ๋ ๊ฐ์
refs์ฌ์ฉ
์๋ชป๋ ์์
์ด ๊ท์น์ ๋ํ ์๋ชป๋ ์ฝ๋ ์์์ ๋๋ค.
// โ ๋ ๋๋ง ์ค์ ref ์ฝ๊ธฐ
function Component() {
const ref = useRef(0);
const value = ref.current; // ๋ ๋๋ง ์ค์ ์ฝ์ง ๋ง์ธ์
return <div>{value}</div>;
}
// โ ๋ ๋๋ง ์ค์ ref ์์
function Component({value}) {
const ref = useRef(null);
ref.current = value; // ๋ ๋๋ง ์ค์ ์์ ํ์ง ๋ง์ธ์
return <div />;
}์ฌ๋ฐ๋ฅธ ์์
์ด ๊ท์น์ ๋ํ ์ฌ๋ฐ๋ฅธ ์ฝ๋ ์์์ ๋๋ค.
// โ
Effect/ํธ๋ค๋ฌ์์ ref ์ฝ๊ธฐ
function Component() {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
console.log(ref.current.offsetWidth); // Effect์์๋ OK
}
});
return <div ref={ref} />;
}
// โ
UI ๊ฐ์๋ state ์ฌ์ฉ
function Component() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
// โ
ref ๊ฐ์ ์ง์ฐ ์ด๊ธฐํ
function Component() {
const ref = useRef(null);
// ์ฒซ ์ฌ์ฉ ์ ํ ๋ฒ๋ง ์ด๊ธฐํ
if (ref.current === null) {
ref.current = expensiveComputation(); // OK - ์ง์ฐ ์ด๊ธฐํ
}
const handleClick = () => {
console.log(ref.current); // ์ด๊ธฐํ๋ ๊ฐ ์ฌ์ฉ
};
return <button onClick={handleClick}>Click</button>;
}๋ฌธ์ ํด๊ฒฐ
๋ฆฐํธ๊ฐ .current๊ฐ ์๋ ์ผ๋ฐ ๊ฐ์ฒด๋ฅผ ํ๋๊ทธ ์ง์ ํ์ต๋๋ค
์ด๋ฆ ํด๋ฆฌ์คํฑ์ ์๋์ ์ผ๋ก ref.current์ fooRef.current๋ฅผ ์ค์ ref๋ก ์ทจ๊ธํฉ๋๋ค. ์ปค์คํ
์ปจํ
์ด๋ ๊ฐ์ฒด๋ฅผ ๋ชจ๋ธ๋งํ๋ ๊ฒฝ์ฐ ๋ค๋ฅธ ์ด๋ฆ(์: box)์ ์ ํํ๊ฑฐ๋ ๊ฐ๋ณ ๊ฐ์ state๋ก ์ด๋ํ์ธ์. ์ด๋ฆ์ ๋ณ๊ฒฝํ๋ฉด ์ปดํ์ผ๋ฌ๊ฐ ref๋ก ์ถ๋ก ํ์ง ์๊ธฐ ๋๋ฌธ์ ๋ฆฐํธ๋ฅผ ํผํ ์ ์์ต๋๋ค.