๐useRef?
const ref = useRef(value)
useRef๋ ์ ์ฅ๊ณต๊ฐ ๋๋ DOM์์์ ์ ๊ทผํ๊ธฐ ์ํด ์ฌ์ฉ๋๋ React Hook์ด๋ค. ์ฌ๊ธฐ์ Ref๋ reference, ์ฆ ์ฐธ์กฐ๋ฅผ ๋ปํ๋ค. ์ฐ๋ฆฌ๊ฐ ์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉ ํ ๋์๋, ํน์ DOM ์ ์ ํํ๊ธฐ ์ํด์ querySelector ๋ฑ์ ํจ์๋ฅผ ์ฌ์ฉํ๋ค.
React๋ฅผ ์ฌ์ฉํ๋ ํ๋ก์ ํธ์์๋ ๊ฐ๋์ฉ DOM ์ ์ง์ ์ ํํด์ผ ํ๋ ์ํฉ์ด ํ์ํ๋ค. ๊ทธ๋ด๋ ์ฐ๋ฆฌ๋ useRef๋ผ๋ React Hook์ ์ฌ์ฉํ๋ค.
ํจ์ํ ์ปดํฌ๋ํธ์์ useRef๋ฅผ ๋ถ๋ฅด๋ฉด ref ์ค๋ธ์ ํธ๋ฅผ ๋ฐํํ๋ค. โปref์ค๋ธ์ ํธ { current : value }
ref ์ค๋ธ์ ํธ๋ ์ธ์ ๋ ์์ ํ ์ ์๋ค. ๋ฐํ๋ ref๋ ์ปดํฌ๋ํธ์ ์ ์์ ์ฃผ๊ธฐ๋ฅผ ํตํด ์ ์ง๊ฐ ๋๋ค.
์ปดํฌ๋ํธ๊ฐ ์ธ๋ง์ดํธ ๋๊ธฐ ์ ๊น์ง๋ ์ ์งํ ์ ์๋ค๋ ์๋ฏธ์ด๋ค.
- useRef๋ .current ํ๋กํผํฐ๋ก ์ ๋ฌ๋ ์ธ์๋ก ์ด๊ธฐํ๋ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ref ๊ฐ์ฒด๋ฅผ ๋ฐํํฉ๋๋ค. ๋ฐํ๋ ๊ฐ์ฒด๋ ์ปดํฌ๋ํธ์ ์ ์์ ์ฃผ๊ธฐ๋ฅผ ํตํด ์ ์ง๋ ๊ฒ์ ๋๋ค.
- useRef๋ .current ํ๋กํผํฐ์ ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๊ฐ์ ๋ด๊ณ ์๋ "์์"์ ๊ฐ์ต๋๋ค.
- ๊ทธ๋ฆฌ๊ณ .current ํ๋กํผํฐ๋ฅผ ๋ณ๊ฒฝํ๋๋ผ๋ ์ด ๊ฒ์ด ๋ฆฌ๋ ๋๋ง์ ๋ฐ์์ํค์ง ์์ต๋๋ค.
useRef๋ฅผ ํตํด ๋ง๋ ref ๊ฐ์ฒด ๋ด๋ถ์ ๊ฐ์, render์ ์๊ด ์์ด ์ ์ง ๋๋ค.
๐useRef๋ ์ธ์ ์ฌ์ฉ๋ ๊น?
1. state์ ๋น์ทํ๊ฒ ์ด๋ค ๊ฐ์ ์ ์ฅํด์ฃผ๋ ์ ์ฅ๊ณต๊ฐ์ผ๋ก ์ฌ์ฉ๋๋ค.
State์ ๋ณํ -> ๋ ๋๋ง -> ์ปดํฌ๋ํธ ๋ด๋ถ ๋ณ์๋ค ์ด๊ธฐํ : ์ํ์ง ์๋ ๋ ๋๋ง ๋๋ฌธ์ ๊ณค๋ํด์ง๋ ๊ฒฝ์ฐ ๋ฐ์
Ref์ ๋ณํ -> ๋ ๋๋ง X -> ๋ณ์๋ค์ ๊ฐ์ด ์ ์ง๋จ
State์ ๋ณํ -> ๋ ๋๋ง -> Ref์ ๊ฐ์ด ์ด๊ธฐ๊ฐ์ผ๋ก ๋๋ ๊ฒ์ด ์๋๋ผ ๋ณํ๋ ๊ฐ์ผ๋ก ์ ์ง๋จ.
useRef๋ ๋ณํ๋ ๊ฐ์งํด์ผํ์ง๋ง ๊ทธ ๋ณํ๊ฐ ๋ ๋๋ง์ ๋ฐ์์ํค๋ฉด ์๋๋ ๊ฐ์ ๋ค๋ฃฐ ๋ ์ฌ์ฉ๋๋ค.
// App Component
function App() {
const [count,setCount] = useState(0);
const renderCount = useRef(0);
useEffect(() => {
renderCount.current = renderCount.current + 1;
console.log("๋ ๋๋ง๋ ์:" , renderCount.current )
})
return (
<div>
<p>count: {count}</p>
<button onClick={() => {setCount(count+1)}}>์ฌ๋ ค!!</button>
</div>
);
}
useEffect ์์ useStateํจ์๋ฅผ ์ผ๋ค๋ฉด ๋ฌดํ ๊ตด๋ ์ ๋น ์ง๋ ํ์์ด ๋ํ๋ฌ์ ๊ฒ์ด๋ค.
ํ์ง๋ง useRef๋ฅผ ์ฌ์ฉํจ์ผ๋ก์จ state๊ฐ์ count์ํจ ์๋งํผ ๋ ๋๋ง๋ ์ซ์๋ฅผ ๋ฐํํ ์ ์๊ฒ ๋์๋ค.
2. Ref๋ฅผ ํตํด DOM์์์ ์ ๊ทผํด์ ์ฌ๋ฌ๊ฐ์ง ์์ ์ ํ ์ ์๋ค.
์) input์์๋ฅผ clickํ์ง ์์๋ focus๋ฅผ ์ฃผ๊ณ ์ถ์ ๋
function App() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
},[])
const login = () => {
alert(`ํ์ํฉ๋๋ค. ${inputRef.current.value}`)
inputRef.current.focus();
}
return (
<div className="wrap">
<input ref={inputRef} type="text" placeholder="username"></input>
<button onClick={login}>๋ก๊ทธ์ธ</button>
</div>
);
}
์ฐธ๊ณ ๋ฌธ์
- https://youtu.be/VxqZrL4FLz8?si=3l8ncQ0oy32hSVBh
- https://ko.reactjs.org/docs/hooks-reference.html#useref
- https://velog.io/@juno7803/React-useRef-200-ํ์ฉํ๊ธฐ
'Frontend > React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
react - redux ์ด์ฉํด์ ๊ณ์ฐ๊ธฐ ๋ง๋ค๊ธฐ (2) | 2023.12.29 |
---|---|
react - redux (0) | 2023.12.24 |
react Lifecycle , useEffect ์์ addEventListener (0) | 2023.11.17 |
react - router ๊ฐ๋ ์ ์ก์ ๋ณด์! (2) | 2023.10.13 |
react - axios๋ ๋ฌด์์ธ๊ฐ? (0) | 2023.10.09 |