Custom Hooks
1. Custom Hooks์ด๋?
๊ฐ๋ฐ์๊ฐ ์ค์ค๋ก ์ปค์คํ ํ ํ ์ ์๋ฏธ
์ด๋ฅผ ์ด์ฉํด ๋ฐ๋ณต๋๋ ๋ก์ง์ ํจ์๋ก ๋ฝ์๋ด์ด ์ฌ์ฌ์ฉ ๊ฐ๋ฅ
(1) Custom Hooks์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
์ฌ๋ฌ url์ fetchํ ๋,
์ฌ๋ฌ input์ ์ํ ์ํ ๋ณ๊ฒฝ ๋ฑ ๋ฐ๋ณต๋๋ ๋ก์ง์ ๋์ผํ ํจ์์์ ์๋ํ๊ฒ ํ๊ณ ์ถ์ ๋.
(2) Custom Hooks์ ์ฅ์
์ํ๊ด๋ฆฌ ๋ก์ง์ ์ฌํ์ฉ์ด ๊ฐ๋ฅ
ํด๋์ค ์ปดํฌ๋ํธ๋ณด๋ค ์ ์ ์์ ์ฝ๋๋ก ๋์ผํ ๋ก์ง์ ๊ตฌํํ ์ ์์ผ๋ฉฐ
ํจ์ํ์ผ๋ก ์์ฑํ๊ธฐ ๋๋ฌธ์ ๋ณด๋ค ๋ช ๋ฃํ๋ค๋ ์ฅ์ ์ด ์์ (e.g.
useSomething
)
2. Custom Hooks ์ฌ์ฉ ์์
์๋ฅผ ๋ค์ด, ์๋์ ๊ฐ์ ์ปดํฌ๋ํธ๊ฐ ์๋ค๋ฉด,
// FriendStatus : ์น๊ตฌ๊ฐ online์ธ์ง offline์ธ์ง returnํ๋ ์ปดํฌ๋ํธ function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } // FriendListItem : ์น๊ตฌ๊ฐ online์ผ ๋ ์ด๋ก์์ผ๋ก ํ์ํ๋ ์ปดํฌ๋ํธ function FriendListItem(props) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); }
๋ ์ปดํฌ๋ํธ์์ ์ฌ์ฉํ๊ธฐ ์ํด ๋์ผํ๊ฒ ์ฌ์ฉ๋๊ณ ์๋ ๋ก์ง์ ๋ถ๋ฆฌํ์ฌ ํจ์
useFriendStatus
์ฌ์ฉ โ Custom Hook์ ์ ์ํ ๋๋ ์๋์ ๊ฐ์ ๊ท์น์ด ํ์(1) Custom Hook์ ์ ์ํ ๋๋ ํจ์ ์ด๋ฆ ์์
use
๋ฅผ ๋ถ์ด๊ธฐ(2) ๋๊ฐ์ ๊ฒฝ์ฐ ํ๋ก์ ํธ ๋ด์ hooks ๋๋ ํ ๋ฆฌ์ Custom Hook์ ์์น์ํค๊ธฐ
(3) Custom Hook์ผ๋ก ๋ง๋ค ๋ ํจ์๋ ์กฐ๊ฑด๋ถ ํจ์๊ฐ ์๋์ด์ผ ํจ. ์ฆ return ํ๋ ๊ฐ์ ์กฐ๊ฑด๋ถ์ฌ์๋ ์ ๋จ. ๋๋ฌธ์ ์์ ์ด
useFriendStatus
Hook์ ์จ๋ผ์ธ ์ํ์ ์ฌ๋ถ๋ฅผ boolean ํ์ ์ผ๋ก ๋ฐํํ๊ณ ์์.
์ด๋ ๊ฒ ๋ง๋ค์ด์ง Custom Hook์ Hook ๋ด๋ถ์
useState
์ ๊ฐ์ React ๋ด์ฅ Hook์ ์ฌ์ฉํ์ฌ ์์ฑ ๊ฐ๋ฅ์ผ๋ฐ ํจ์ ๋ด๋ถ์์๋ React ๋ด์ฅ Hook์ ๋ถ๋ฌ ์ฌ์ฉํ ์ ์์ง๋ง Custom Hook์์๋ ๊ฐ๋ฅํจ.
useFriendStatus
Hook์ ๋ ์ปดํฌ๋ํธ์ ์ ์ฉํ ์ฝ๋function FriendStatus(props) { const isOnline = useFriendStatus(props.friend.id); // useFriendStatus Hook ์ ์ฉ if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); }
๋ก์ง์ ๋ถ๋ฆฌํด Custom Hook์ผ๋ก ๋ง๋ค์๊ธฐ ๋๋ฌธ์ ๋ ์ปดํฌ๋ํธ๋ ๋ ์ง๊ด์ ์ผ๋ก ํ์ธ์ด ๊ฐ๋ฅํด์ง.
๊ทธ๋ฌ๋ ๊ฐ์ Custom Hook์ ์ฌ์ฉํ๋ค๊ณ ํด์ ๋ ๊ฐ์ ์ปดํฌ๋ํธ๊ฐ ๊ฐ์ state๋ฅผ ๊ณต์ ํ๋ ๊ฒ์ ์๋. ๊ทธ์ ๋ก์ง๋ง ๊ณต์ ํ ๋ฟ, state๋ ์ปดํฌ๋ํธ ๋ด์์ ๋ ๋ฆฝ์ ์ผ๋ก ์ ์๋์ด ์์.
Last updated