π‘ 컀μ€ν ν μ μ΄μ©ν΄ μ»΄ν¬λνΈ λ‘μ§μ ν¨μλ‘ λ§λ€μ΄ μ¬μ¬μ©ν μ μλ€.
// FriendStatus
import React, { useState, useEffect } from 'react';
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
import React, { useState, useEffect } from 'react';
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>
);
}
use
λ‘ μμνλ μλ°μ€ν¬λ¦½νΈ ν¨μμ΄λ€.Hook
(리μ‘νΈμμ μ 곡νλ ν
λ±)μ νΈμΆν μ μλ€.import { useState, useEffect } from 'react';
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});
return isOnline;
}
// FriendStatus
function FriendStatus(props) {
const isOnline = useFriendState(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
// FriendListItem
import React, { useState, useEffect } from 'react';
function FriendListItem(props) {
const isOnline = useFriendState(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}
Hook
μ μ¬μ©νλ μ»΄ν¬λνΈλ state
λ₯Ό 곡μ νμ§ μλλ€.state
λ₯Ό λ°λλ€. React
κ΄μ μμ λ¨μν κ° μ»΄ν¬λνΈμμ useState
μ useEffect
λ₯Ό νΈμΆν κ²μ΄κΈ° λλ¬Έμ κ° μ»΄ν¬λνΈμ state
μ effect
λ λ
립μ μ΄λ€.Hook
μ ν¨μμ΄κΈ° λλ¬Έμ Hook
μ¬μ΄μμλ μ 보λ₯Ό μ λ¬ν μ μλ€.
const friendList = [
{ id: 1, name: 'Phoebe' },
{ id: 2, name: 'Rachel' },
{ id: 3, name: 'Ross' },
];
function ChatRecipientPicker() {
const [recipientID, setRecipientID] = useState(1);
const isRecipientOnline = useFriendStatus(recipientID);
return (
<>
<Circle color={isRecipientOnline ? 'green' : 'red'} />
<select
value={recipientID}
onChange={e => setRecipientID(Number(e.target.value))}
>
{friendList.map(friend => (
<option key={friend.id} value={friend.id}>
{friend.name}
</option>
))}
</select>
</>
);
}
recipientID
λ₯Ό μ
λ°μ΄νΈνλ©΄ useFriendStatus
Hookμ μ΄λ―Έ μ νλμ΄ μλ μΉκ΅¬μ ꡬλ
μ ν΄μ§νκ³ μλ‘ μ νλ μΉκ΅¬μ μνλ₯Ό ꡬλ
ν κ²μ΄λ€.μ°Έκ³ : React 곡μλ¬Έμ