The new adventures of Captain Hook

Jakub Fedoruk
Pragmatists
Published in
2 min readOct 6, 2020

--

by Michał Rosiński

Creating a custom React Hook step-by-step

In this post, I’d like to show you how to easily create your first custom React Hook.

I hope you’ve read my previous post: Ahoy Captain Hook — let’s use it as a starting point.

Custom Hooks

The reason for creating a custom Hook is to extract component logic into reusable functions.

During our previous encounter, the Lost Boys created a High Order Component (HOC) withDebounce that allows wrapping the component’s onChange and onBlur in lodash’s debounce function.

While this approach gives a lot of flexibility, we can go further and re-factor this to a custom Hook. This allows to reuse the logic and hide the implementation details with easy-to-use function.

The simple approach

In my opinion this particular example is not well suited for Hooks, but my goal here is to show you how to do it, not discuss whether it should be done or not.

Here’s the HOC we will try to rewrite to a Hook.

withDebounceLostBoys.js

The simplest and easiest approach is to copy the whole logic-related code from the HOC into our custom Hook.

useDebounce — step 1

Of course this won’t work 😉

The right approach

Our custom Hook should hide the implementation details but provide functionality. As we could see in the simple approach, nothing was returned from the Hook. It was an obvious error.

Let me walk you through the changes:

  • The hook is now a function that returns an object
  • We provide function handlers which are then wrapped with our custom logic
  • We provide value instead of reading component props

Testing

Testing the right approach is very simple — the only thing we need to do is change the component under test.

Instead of wrapping the component with a HOC, we can use the new Hook inside it.

The rest of the test logic remains exactly the same.

Summary

I hope that now you have enough knowledge to start playing with custom Hooks.

If you want to read more about it, please go to the official docs.

You can find the code on Pragmatists Github.

Please check my other posts https://medium.com/@jakub.fedoruk and our official blog https://blog.pragmatists.com/.

Thanks for reading!

--

--