https://ko.react.dev/reference/react/useRef
๋ ๋๋ง์ ํ์ํ์ง ์์ ๊ฐ์ ์ฐธ์กฐํ ์ ์๋ Hook
const ref = useRef(initialValue)Caveats
ref.current๋ mutate ๊ฐ๋ฅํ๋ค. ํ์ง๋ง ๋ ๋๋ง์ ์ฌ์ฉ๋๋ ๊ฐ์ฒด(state์ ์ผ๋ถ)๋ฅผ ํฌํจํ๋ ๊ฒฝ์ฐ mutateํด์๋ ์๋๋ค.ref.current๋ ๋ณ๊ฒฝํด๋ ์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋ ๋๋ง๋์ง ์๋๋ค. React๋ ํด๋น ๊ฐ์ด ์ธ์ ๋ฐ๋์๋์ง ์์ง ๋ชปํ๋ค.- ์ด๊ธฐํ๋ฅผ ์ ์ธํ๊ณ ๋ ๋๋ง ์ค์
ref.current๋ฅผ ์ฐ๊ฑฐ๋ ์ฝ์ผ๋ฉด ์๋๋ค. - Strict Mode ์์๋ React๋ ์ปดํฌ๋ํธ ํจ์๋ฅผ ๋๋ฒ ํธ์ถํ๋ค. useRef๋ ๋ง์ฐฌ๊ฐ์ง๋ผ ref ๊ฐ์ฒด๋ ๋ ๋ฒ ์์ฑ๋๊ณ ํ๋๋ ๋ฒ๋ ค์ง๋ค.
Usage
Referencing a value with a ref
ref๋ ๋ณ๊ฒฝ ์ ๋ฆฌ๋ ๋๋ง์ ์ด๋ฐํ์ง ์๋๋ค. ๋ฐ๋ผ์ UI์ ์ํฅ์ ๋ฏธ์น๋ ์ ๋ณด๋ฅผ ์ ์ฅํ๋ฉด ์๋๊ณ , intervalId ๊ฐ์ด UI์ ์ํฅ์ ๋ฏธ์น์ง ์๋ ๊ฐ์ ์ ์ฅํด์ผํ๋ค.
ref๋ ๋ํ ๋ค์์ ๋ณด์ฅํ๋ค.
- ๋ฆฌ๋ ๋๋ง ์ฌ์ด์ ์ ๋ณด๋ฅผ ์ ์ฅํ ์ ์๋ค.
- ๋ฆฌ๋ ๋๋ง์ ์ด๋ฐํ์ง ์๋๋ค.
- ๊ฐ๊ฐ์ ์ปดํฌ๋ํธ์ ๋ก์ปฌ๋ก ์ ์ฅ๋๋ค.
Do not write or read ref.current during rendering
React๋ ์ปดํฌ๋ํธ ๋ณธ๋ฌธ์ด ์์ํจ์์ฒ๋ผ ๋์ํ๊ธฐ๋ฅผ ์ํ๋ค. ์ ๋ ฅ๊ฐ(props, state, context)๊ฐ ๋๊ฐ์ผ๋ฉด ๋๊ฐ์ JSX๊ฐ ๋์์ผํ๋ค. ๋ ๋๋ง ์ค์ ref๋ฅผ ์ฝ๊ฑฐ๋ ์ฐ๋ฉด ์ด๋ฌํ ๊ธฐ๋๊ฐ ๊นจ์ง๋ค.
function MyComponent() {
// ๐ฉ ๋ ๋๋ง ์ค์ ref๋ฅผ ์์ฑํ์ง ๋ง์ธ์.
myRef.current = 123;
// ๐ฉ ๋ ๋๋ง ์ค์ ref๋ฅผ ์ฝ์ง ๋ง์ธ์.
return <h1>{myOtherRef.current}</h1>;
}๋์ ์ด๋ฒคํธ ํธ๋ค๋ฌ๋ Effect์์๋ ์ฝ๊ฑฐ๋ ์ธ ์ ์๋ค.
function MyComponent() {
// ...
useEffect(() => {
// โ
Effect์์ ref๋ฅผ ์ฝ๊ฑฐ๋ ์ธ ์ ์์ต๋๋ค.
myRef.current = 123;
});
// ...
function handleClick() {
// โ
์ด๋ฒคํธ ํธ๋ค๋ฌ์์ ref๋ฅผ ์ฝ๊ฑฐ๋ ์ธ ์ ์์ต๋๋ค.
doSomething(myOtherRef.current);
}
}Avoiding recreating the ref contents
ref ์ด๊ธฐ ๊ฐ์ ํ๋ฒ ์ ์ฅํ๊ณ ๋ค์ ๋ ๋๋ง๋ถํฐ๋ ๋ฌด์ํ์ง๋ง, ์๋์ ๊ฐ์ ๊ฒฝ์ฐ ํธ์ถ ์์ฒด๋ ๋งค๋ฒ ์ด๋ฃจ์ด์ง๋ค.
function Video() {
const playerRef = useRef(new VideoPlayer());๋ฐ๋ผ์ ๋ค์๊ณผ ๊ฐ์ด ์ด๊ธฐํ์ธ ๊ฒฝ์ฐ์ ํํ์ฌ ๋ ๋๋ง ์ค์ ref.current๋ฅผ ์ฝ๊ณ ์ฐ๋ ์์
์ ํตํด ๋ญ๋น๋ฅผ ์ค์ผ ์ ์๋ค.
function Video() {
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}์ด๊ฒฝ์ฐ ๊ฒฐ๊ณผ๊ฐ ํญ์ ๋์ผํ๊ณ , ์ด๊ธฐํ ์ค์๋ง ์กฐ๊ฑด์ด ์คํ๋๋ฏ๋ก ์์๊ฐ๋ฅํ์ฌ ๊ด์ฐฎ๋ค.
get ref to a custom component
๊ธฐ๋ณธ์ ์ผ๋ก ์ปดํฌ๋ํธ๋ ๋ด๋ถ์ DOM ๋
ธ๋์ ๋ํ ref๋ฅผ ์ธ๋ถ๋ก ๋
ธ์ถํ์ง ์๋๋ค. ๋ฐ๋ผ์ ์ปค์คํ
์ปดํฌ๋ํธ์ ๋ํ ref๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ๋ค์๊ณผ ๊ฐ์ด forwardRef๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
import { forwardRef } from 'react';
const MyInput = forwardRef(({ value, onChange }, ref) => {
return (
<input
value={value}
onChange={onChange}
ref={ref}
/>
);
});