Reader small image

You're reading from  Learn React Hooks

Product typeBook
Published inOct 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838641443
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Daniel Bugl
Daniel Bugl
author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl

Right arrow

Building Your Own Hooks

In the previous chapter, we learned about the limitations and rules of Hooks. We learned where to call Hooks, why the order of Hooks matters, and the naming conventions for Hooks. Finally, we learned about enforcing the rules of Hooks and dealing with useEffect dependencies.

In this chapter, we are going to learn how to create custom Hooks by extracting existing code from our components. We are also going to learn how to use custom Hooks and how Hooks can interact with each other. Then, we are going to learn how to write tests for our custom Hooks. Finally, we are going to learn about the full React Hooks API.

The following topics will be covered in this chapter:

  • Extracting custom Hooks
  • Using custom Hooks
  • Interactions between Hooks
  • Testing Hooks
  • Exploring the React Hooks API

Technical requirements

A fairly recent version of Node.js should already be installed (v11.12.0 or higher). The npm package manager for Node.js also needs to be installed.

The code for this chapter can be found on GitHub: https://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter10.

Check out the following video to see the code in action:

http://bit.ly/2Mm9yoC

Please note that it is highly recommended that you write the code on your own. Do not simply run the code examples provided previously. It is important to write the code yourself in order to learn and understand properly. However, if you run into any issues, you can always refer to the code example.

Now let's get started with the chapter.

Extracting custom Hooks

After getting a good grasp on the concept of Hooks by learning about the State and Effect Hooks, community Hooks, and the rules of Hooks, we are now going to build our own Hooks. We start by extracting custom Hooks from existing functionalities of our blog application. Usually, it makes the most sense to first write the component, and then later extract a custom Hook from it if we notice that we use similar code across multiple components. Doing so avoids prematurely defining custom Hooks and making our project unnecessarily complex.

We are going to extract the following Hooks in this section:

  • A useTheme Hook
  • The useUserState and usePostsState Hooks
  • A useDispatch Hook
  • API Hooks
  • A useDebouncedUndo Hook

Creating a useTheme Hook

...

Using our custom Hooks

After creating our custom Hooks, we can now start using them throughout our blog application. Using custom Hooks is quite straightforward as they are similar to community Hooks. Just like all other Hooks, custom Hooks are simply JavaScript functions.

We created the following Hooks:

  • useTheme
  • useDispatch
  • usePostsState
  • useUserState
  • useDebouncedUndo
  • useAPILogin
  • useAPIRegister
  • useAPICreatePost
  • useAPIThemes

In this section, we are going to refactor our app to use all of our custom Hooks.

Using the useTheme Hook

Instead of using the useContext Hook with the ThemeContext, we can now use the useTheme Hook directly! If we end up changing the theming system later on, we can simply modify the useTheme Hook and...

Interactions between Hooks

Our whole blog app now works in the same way as before, but it uses our custom Hooks! Until now, we have always had Hooks that encapsulated the whole logic, with only constant values being passed as arguments to our custom Hooks. However, we can also pass values of other Hooks into custom Hooks!

Since Hooks are simply JavaScript functions, all Hooks can accept any value as arguments and work with them: constant values, component props, or even values from other Hooks.

We are now going to create local Hooks, which means that they will be placed in the same file as the component, because they are not needed anywhere else. However, they will still make our code easier to read and maintain. These local Hooks will accept values from other Hooks as arguments.

The following local Hooks will be created:

  • A local Register Effect Hook
  • A local Login Effect Hook...

Testing Hooks

Now our blog application makes full use of Hooks! We even defined custom Hooks for various functions to make our code more reusable, concise, and easy to read.

When defining custom Hooks, it makes sense to write tests for them to ensure they work properly, even when we change them later on or add more options.

To test our Hooks, we are going to use the Jest test runner, which is included in our create-react-app project. However, as a result of the rules of Hooks, we cannot call Hooks from the test functions because they can only be called inside the body of a function component.

Because we do not want to create a component specifically for each test, we are going to use the React Hooks Testing Library to test Hooks directly. This library actually creates a test component and provides various utility functions to interact with the Hook.

...

Exploring the React Hooks API

The official React library provides certain built-in Hooks, which can be used to create custom Hooks. We have already learned about the three basic Hooks that React provides:

  • useState
  • useEffect
  • useContext

Additionally, React provides more advanced Hooks, which can be very useful in certain use cases:

  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

The useState Hook

The useState Hook returns a value that will persist across re-renders, and a function to update it. A value for the initialState can be passed to it as an argument:

const [ state, setState ] = useState(initialState)

Calling setState updates the value and re-renders the component with the updated...

Summary

In this chapter, we first learned how to extract custom Hooks from existing code in our blog app. We extracted various Context Hooks into custom Hooks, then created API Hooks and a more advanced Hook for debounced undo functionality. Next, we learned about interactions between Hooks and how we can use values from other Hooks in custom Hooks. We then created local Hooks for our blog app. Then, we learned about testing various Hooks with Jest and the React Hooks Testing Library. Finally, we learned about all the Hooks provided by the React Hooks API, at the time of writing.

Knowing when and how to extract custom Hooks is a very important skill in React development. In a larger project, we are probably going to define many custom Hooks, specifically tailored to our project's needs. Custom Hooks can also make it easier to maintain our application, as we only need to adjust...

Questions

To recap what we have learned in this chapter, try answering the following questions:

  1. How can we extract a custom Hook from existing code?
  2. What is the advantage of creating API Hooks?
  3. When should we extract functionality into a custom Hook?
  4. How do we use custom Hooks?
  5. When should we create local Hooks?
  6. Which interactions between Hooks are possible?
  7. Which library can we use to test Hooks?
  8. How can we test Hook actions?
  9. How can we test contexts?
  10. How can we test asynchronous code?

Further reading

If you are interested in more information about the concepts we learned in this chapter, take a look at the following reading material:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React Hooks
Published in: Oct 2019Publisher: PacktISBN-13: 9781838641443
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl