Member-only story
React custom hooks allow extracting component logic into reusable functions. By separating concerns into standalone hooks, components transform into clean, focused rending pure functions.
In this article we’ll how crafting your own hooks unlocks excellent reusability, testing, and separation of UI code.
Motivating Custom Hooks
Imagine we have a FriendStatus component:
function FriendStatus() {
const [friends, setFriends] = useState([]);
useEffect(() => {
// fetch friends
}, []);
useEffect(() => {
// sub to updates
}, [friends]);
const isOnline = friend =>
friends.includes(friend);
return (
<div>
{props.friend.name} is
{isOnline(props.friend) ? 'Online' : 'Offline'}
</div>
);
}
It manages friends state and checks status. Now imagine reusing the isOnline() check elsewhere — we’d have to duplicate all the logic!
Instead, we extract it:
function useFriendStatus(friendID) {
const [friends, setFriends] = useState([]);
useEffect(() => {
// fetch friends
}, []);
useEffect(() => {
// sub to updates
}, [friends]);
return friends.includes(friendID);
}