Member-only story

Simplifying React with Custom Hooks

Extracting Logic for Readable Components

Max N
2 min readFeb 19, 2024

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);

}

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet