Using Custom Hooks to Reuse Logic

Baisali Pradhan
4 min readDec 12, 2023

--

React is a free and open-source front-end JavaScript library used to create user interfaces using components. React comes with several built-in hooks, like useState, useContext, and useEffect.

But sometimes, I wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. But now I can create my own Hooks for my application’s needs.

Let’s say we are building a chat application that heavily relies on the network. I want to warn the user if their network connection has accidentally gone off while they were using my app.

Here I need two things in my component:

  1. A piece of state that tracks whether the network is online.
  2. An Effect that subscribes to the global online and offline events, and updates that state.

This will keep your component synchronized with the network status. You might start with something like this:

When your network is on, It will show as online
When your network is off, It will show as offline

Now if I also want to use the same logic in a different component. i.e. I want to implement a Save button that will become disabled and show “Reconnecting…” instead of “Save” while the network is off.

import React, { useState, useEffect } from "react";

export default function App() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);

function handleSaveClick() {
console.log("✅ Progress saved");
}

return (
<button disabled={!isOnline} onClick={handleSaveClick}>
{isOnline ? "SAVE" : "Reconnecting..."}
</button>
);
}
When the Network is on, it will show a save
When the Network is off, it will show Reconnecting…

While these two parts function well together, it is regrettable that their logic is redundant. Despite their dissimilar looks, it appears that you wish to apply the same reasoning between them.

Extracting your own custom Hook from a component:

For the sake of this brief thought, suppose there was an integrated useOnlineStatus Hook that worked similarly to useState and useEffect. By doing so, you could eliminate any overlap between these two elements and simplify both of them.

You can create your own built-in Hook even though there isn’t one. Create a function named useOnlineStatus and transfer all of the redundant code from the previously written components into it:

When the network is on
When the network is off

The amount of repetitive logic in your components has decreased. Furthermore, rather than describing how to accomplish it (by subscribing to the browser events), the code inside them specifies what they want to do (use the online status!).

React applications are built from components. Components are built from Hooks, whether built-in or custom. You’ll likely often use custom Hooks created by others, but occasionally you might write one yourself

  1. Hook names must start with use followed by a capital letter, like useState (built-in) or useOnlineStatus (custom, like earlier on the page). Hooks may return arbitrary values.

Here I’m providing the link to my code-sandbox so you can access the source code: https://codesandbox.io/p/sandbox/react-compiler-forked-w49h5v?file=%2Fsrc%2FuserOnlineStatus.js

Please take note of the following reference: https://react.dev/learn/reusing-logic-with-custom-hooks.

--

--