4. useRef & Custom Hook
useRef
Hook์ ๊ท์น
๊ฐ์ ์ ๋ฆฌ
useRef
useRef๋ ๊ฐ์ ์ฐธ์กฐํ๊ธฐ ์ํ ๊ฐ์ฒด์ด๋ค. ์ํ๋ ์๊ด์์ด ๊ฐ์ ๊ณ์ ์ ์งํ๊ณ ์ถ์ ๋ useRef๋ฅผ ์ฌ์ฉํ๋ค.
๊ทธ๋ฌ๋ฉด ์๋ ์ฝ๋์ ๊ฐ์ด Component์์ ๊ทธ๋ฅ ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ฉด ๋์ง ์์๊น? ๋ผ๋ ์๋ฌธ์ด ๋ค ๊ฒ ๊ฐ๋ค. ์๋์ ๊ฐ์ด ์์ฑํ๊ฒ ๋๋ฉด ์ปดํฌ๋ํธ๊ฐ ๋ ๋๋ง์ด ๋ ๋๋ง๋ค ์๋กญ๊ฒ ref ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค.
export default function Component {
const ref = {
value: 1
}
ref.value = 2
}
๊ทธ๋ ๋ค๋ฉด ์ปดํฌ๋ํธ ์ธ๋ถ์ ์์ฑํ๋ฉด ์ด๋จ๊น? ์ด๋ ๊ฒ ์์ฑํ ๊ฒฝ์ฐ์ ๋ฌธ์ ์ ์ Component๊ฐ ์ฌ๋ฌ๊ฐ ๋ ๋๋ง์ด ๋๋ฉด ์ฌ๋ฌ Component๊ฐ ๋์ผํ ref๋ฅผ ์ฐธ์กฐํ๊ฒ ๋๋ค. ๋ฐ๋ผ์ ์ปดํฌ๋ํธ ๊ฐ์ธ์ ref๋ฅผ ๊ฐ์ง์๊ฐ ์๋ค.
const ref = {
value: 1
}
export default function Component {
ref.value = 2
}
์ด๋ฅผ ์ํด์ Component์์๋ ref๋ฅผ ์ฌ์ฉํ๊ฒ ๋๋ค.
import { useRef } from 'react';
export default function Component {
const ref = useRef(1);
ref.current += 1;
}
ref๋ state์ ๋ค๋ฅด๊ฒ ๊ฐ์ด ๋ณ๊ฒฝ๋์ด๋ ๋ฆฌ๋ ๋๋ง์ trigger๊ฐ ๋์ง ์๋๋ค. ์ฃผ์ ์ฉ๋:
์ปดํฌ๋ํธ๊ฐ ์ฌ๋ผ์ง ๋๊น์ง ๋์ผํ ๊ฐ์ ์จ์ผ ํ๋ ๊ฒฝ์ฐ -> input๋ฑ์ id ๊ด๋ฆฌ
(ํนํ useEffect ๋ฑ๊ณผ ํจ๊ป ์ฐ๋ฉด์ ๋ง๋๊ฒ ๋๋) ๋น๋๊ธฐ ์ํฉ์์ ํ์ฌ ๊ฐ์ ์ ๋๋ก ์ฐ๊ณ ์ถ์ ๊ฒฝ์ฐ.
useEffect๋ ์ฒ์ ๋ ๋๋ง๋์ setup function์ด ์คํ ๋์์ ๋์ ํ๊ฒฝ์ ๊ธฐ์ตํ๋ค. ๋ฐ๋ผ์ ๋ ๋๋ง ์ดํ์ state๊ฐ ๋ณ๊ฒฝ๋์ด๋ ๋ณ๊ฒฝ๋ ๊ฐ์ ์ฐธ์กฐํ์ง ์๋๋ค.
useEffect(() => {
setTimeout(() => {
console.log(filterText);
}, 5_000);
}, []);
Custom Hook
Component ๋ด๋ถ์ ๋๋ฉ์ธ ๋ก์ง์ ์ฌ์ฌ์ฉํ๊ธฐ ์ํ ์ ์ผ ์ฌ์ด ๋ฐฉ๋ฒ ์ปดํฌ๋ํธ์์ ์์ฑํ ์ฝ๋๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ๊ฐ์ use prefix๋ฅผ ๋ถ์ธ ํ์ผ๋ก ์ถ์ถํ๋ฉด ๋๋ค.
function useFetchProducts() {
const [products, setProducts] = useState<Product[]>([]);
useEffect(() => {
const fetchProducts = async () => {
const url = 'http://localhost:3000/products';
const response = await fetch(url);
const data = await response.json();
setProducts(data.products);
};
fetchProducts();
}, []);
return products;
}
Custom Hook์ ์ปดํฌ๋ํธ์์ ๋๋ฉ์ธ ๋ก์ง์ ๋ถ๋ฆฌํ๋ค. ๊ณต์๋ฌธ์์๋ ์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ์ฌ์ฉ๋๋ ๋ก์ง์ ๊ฒฝ์ฐ ์ ์ฌ์ฉ์ ์ํด ๋ถ๋ฆฌํ๋ค๊ณ ๋์์๋๋ฐ ๊ผญ ์ฌ๋ฌ๊ณณ์์ ์ฌ์ฉ๋๋ ๊ฒ์ด ์๋์ด๋ ๊ด์ฌ์ฌ์ ๋ถ๋ฆฌ๋ฅผ ์ํด Custom Hook์ผ๋ก ๋ถ๋ฆฌํ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ๋ค. ์ค์ ๋ด๋ถ ๊ตฌํ์ ์ด๋ป๊ฒ ๋์ด์๋์ง ์ฌ์ฉํ๋ Component์์ ์ ๊ฒฝ์ฐ์ง ์๋๋ค.
Hook ๊ท์น
Hook์ Component์ ์ต์์์์๋ง ํธ์ถํด์ผ ํ๋ค.
if (playing) {
const products = useFetchProducts();
console.log(products);
}
๋ง์ฝ ํน์ ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ์ ๋ data fetching์ ํ๋ ค๊ณ ํ๋ ๊ฒฝ์ฐ์๋ Custom Hook ์์ฒด๋ฅผ ํธ์ถํ๋ ๊ฒ์ด ์๋๋ผ, Custom Hook ๋ด๋ถ์ data fetching ํจ์๋ฅผ ์คํํ๋ค.
Last updated