Hooking the hooks

Erez Carmel
Israeli Tech Radar

--

Let’s say you have an external React hooks library you want to use, but also have your own custom hooks, how do you handle all your hooks altogether?

I come across this question during a React project I’m working on.

The development team I’m working with is willing to use the ahooks library. A nice useful library that gives you tons of React hooks for your app development. Of course, they also develop their own custom hooks for their app.

The first question I asked them was “How do you plan to use hooks in your app?”

As I expected, they thought about importing the external library directly in their React components, and also importing their custom hooks at the same time.

Oh, no. Not on my shift.

When using external libraries in your app, keep in mind that you might replace it with a better, newer, fancy-schmancy library that will show up someday.

The right approach, in my opinion, is wrapping external libraries with internal util and exposing stable APIs for this util. That way, if you replace the external library, you don’t need to update 100’s of code implementation of this library across your app.

Back to our case, I decided to wrap all the hooks, both external and internal, in one internal hook:

import * as hooks from "ahooks";
import useOnline from "./use-online";
const useHooks = () => {
return {
...hooks,
useOnline
};
};
export default useHooks;

I’ve created a useHooks hook and imported both ahooks and my own useOnline custom hook. The only thing my hook does is spreading ahook adding my custom hook, and return a new object with all the hooks altogether.

Pretty simple.

Now, anywhere in the React app, I don’t care which external hooks library we’ll use, the developers only need to use the useHook to get any custom hook:

const {useOnline, useToggle} = useHooks();const [state, { toggle }] = useToggle();
const onlineStatus = useOnline();

In this example, the useToggle hook comes from the ahook library, but I also have my custom useOnline hook available.

That’s my 5 cents for today. Let me know what you think.

--

--

Erez Carmel
Israeli Tech Radar

Full stack developer, consultant & lecturer, experienced with developing interfaces on various platforms.