Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learn React Hooks

You're reading from  Learn React Hooks

Product type Book
Published in Oct 2019
Publisher Packt
ISBN-13 9781838641443
Pages 426 pages
Edition 1st Edition
Languages
Author (1):
Daniel Bugl Daniel Bugl
Profile icon Daniel Bugl

Table of Contents (19) Chapters

Preface 1. Section 1: Introduction to Hooks
2. Introducing React and React Hooks 3. Using the State Hook 4. Writing Your First Application with React Hooks 5. Section 2: Understanding Hooks in Depth
6. Using the Reducer and Effect Hooks 7. Implementing React Context 8. Implementing Requests and React Suspense 9. Using Hooks for Routing 10. Using Community Hooks 11. Rules of Hooks 12. Building Your Own Hooks 13. Section 3: Integration and Migration
14. Migrating from React Class Components 15. Redux and Hooks 16. MobX and Hooks 17. Assessments 18. Other Books You May Enjoy

Rules of Hooks

In the previous chapter, we learned about using various Hooks that have been developed by the React community, as well as where to find more of them. We learned about replacing React life cycle methods with Hooks, utility and data management Hooks, responsive design with Hooks, and implementing undo/redo functionality with Hooks. Finally, we learned where to find other Hooks.

In this chapter, we are going to learn about everything that there is to know about using Hooks, and what to watch out for when using and developing our own Hooks. Hooks have certain limitations regarding the order that they are called. Violating the rules of Hooks can cause bugs or unexpected behavior, so we need to make sure that we learn and enforce the rules.

The following topics will be covered in this chapter:

  • Calling Hooks
  • Order of Hooks
  • Names of Hooks
  • Enforcing the rules of Hooks
  • Dealing...

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 the GitHub repository: https://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter09.

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 that have been provided. 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.

Calling Hooks

Hooks should only be called in React function components or custom Hooks. They cannot be used in class components or regular JavaScript functions.

Hooks can be called at the top level of the following:

  • React function components
  • Custom Hooks (we are going to learn about creating custom Hooks in the next chapter)

As we can see, Hooks are mostly normal JavaScript functions, except that they rely on being defined in a React function component. Of course, custom Hooks that use other Hooks can be defined outside of React function components, but when using Hooks, we always need to make sure that we call them inside a React function component. Next, we are going to learn about the rules regarding the order of Hooks.

Order of Hooks

Only call Hooks at the top level/beginning of function components or custom Hooks.

Do not call Hooks inside conditions, loops, or nested functions—doing so changes the order of Hooks, which causes bugs. We have already learned that changing the order of Hooks causes the state to get mixed up between multiple Hooks.

In Chapter 2, Using the State Hook, we learned that we cannot do the following:

const [ enableFirstName, setEnableFirstName ] = useState(false)
const [ name, setName ] = enableFirstName
? useState('')
: [ '', () => {} ]
const [ lastName, setLastName ] = useState('')

We rendered a checkbox and two input fields for the firstName and lastName, and then we entered some text in the lastName field:

Revisiting our example from Chapter 2, Using the State Hook

At the moment, the order of Hooks is as follows:

  1. enableFirstName...

Names of Hooks

There is a convention that Hook functions should always be prefixed with use, followed by the Hook name starting with a capital letter; for example: useState, useEffect, and useResource. This is important, because otherwise we would not know which JavaScript functions are Hooks, and which are not. Especially when enforcing the rules of Hooks, we need to know which functions are Hooks so that we can make sure they are not being called conditionally or in loops.

As we can see, naming conventions are not technically required, but they make life a lot easier for developers. Knowing the difference between normal functions and Hooks makes it very easy to automatically enforce the rules of Hooks. In the next section, we are going to learn how to automatically enforce the rules using the eslint tool.

Enforcing the rules of Hooks

If we stick to the convention of prefixing Hook functions with use, we can automatically enforce the other two rules:

  • Only call Hooks from React function components or custom Hooks
  • Only call Hooks at the top level (not inside loops, conditions, or nested functions)

In order to enforce the rules automatically, React provides an eslint plugin called eslint-plugin-react-hooks, which will automatically detect when Hooks are used, and will ensure that the rules are not broken. ESLint is a linter, which is a tool that analyzes source code and finds problems such as stylistic mistakes, potential bugs, and programming errors.

In the future, create-react-app is going to include this plugin by default.

Setting up eslint-plugin-react-hooks

...

Dealing with useEffect dependencies

In addition to enforcing the rules of Hooks, we are also checking whether all the variables that are used in an Effect Hook are passed to its dependency array. This exhaustive dependencies rule ensures that whenever something that is used inside the Effect Hook changes (a function, value, and so on), the Hook will trigger again.

As we have seen in the previous section, there are a couple warnings related to the exhaustive dependencies rule when running the linter with npm run lint. Often, it has to do with the dispatch function or other functions not being part of the dependency array. Usually, these functions should not change, but we can never be sure, so it is better to just add them to the dependencies.

Automatically fixing warnings with eslint...

Summary

In this chapter, we first learned about two rules of Hooks: that we should only call Hooks from React function components, and that we need to ensure that the order of Hooks stays the same. Furthermore, we learned about the naming convention of Hooks, and that they should always start with the use prefix. Then, we learned how to enforce the rules of Hooks using eslint. Finally, we learned about useEffect dependencies, and how to fix missing dependencies automatically using eslint.

Knowing about the rules of Hooks, and enforcing them, is very important in order to avoid bugs and unexpected behavior. These rules will be especially important when creating our own Hooks. Now that we have a good grasp on how Hooks work, including their rules and conventions, in the next chapter, we are going to learn how to create our own Hooks!

...

Questions

In order to recap what we have learned in this chapter, try answering the following questions:

  1. Where can Hooks be called?
  2. Can we use Hooks in React class components?
  3. What do we need to watch out for regarding the order of Hooks?
  4. Can Hooks be called inside conditions, loops, or nested functions?
  5. What is the naming convention for Hooks?
  6. How can we automatically enforce the rules of Hooks?
  7. What is the exhaustive dependencies rule?
  8. How can we automatically fix linter warnings?

Further reading

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learn React Hooks
Published in: Oct 2019 Publisher: Packt ISBN-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.
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}