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

Using the State Hook

Now that you've learned about the principles of React and had an introduction to Hooks, we are going to learn about the State Hook in depth. We will start by learning how the State Hook works internally by reimplementing it ourselves. Next, we learn about some of the limitations of Hooks, and why they exist. Then, we will learn about possible alternative Hook APIs and their associated problems. Finally, we learn how to solve the common problems that result from the limitations of Hooks. By the end of this chapter, we will know how to use the State Hook in order to implement stateful function components in React.

The following topics will be covered in this chapter:

  • Reimplementing the useState Hook as a simple function, which accesses the global state
  • Comparing our reimplementation to real React Hooks and learning about the differences
  • Learning about...

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

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 previously provided. It is important that you write the code yourself so that you learn and understand it properly. However, if you run into any issues, you can always refer to the code example.

Now, let's get started with the chapter.

Reimplementing the useState function

In order to get a better understanding of how Hooks work internally, we are going to reimplement the useState Hook from scratch. However, we are not going to implement it as an actual React Hook, but as a simple JavaScript function—just to get an idea of what Hooks are actually doing.

Please note that this reimplementation is not exactly how React Hooks work internally. The actual implementation is similar, and thus, it has similar constraints. However, the real implementation is much more complicated than what we will be implementing here.

We are now going to start reimplementing the State Hook:

  1. First, we copy the code from chapter1_2, where we are going to replace the current useState Hook with our own implementation.
  2. Open src/App.js and remove the import of the Hook by removing the following line:
import React, { useState } from...

Problems with our simple Hook implementation

If we run our Hook implementation now, we are going to notice that when our component rerenders, the state gets reset, so we cannot enter any text in the field. This is due to the reinitialization of the value variable every time our component gets rendered, which happens because we call useState each time we render the component.

In the upcoming sections, we are going to solve this problem by using a global variable and then turn the simple value into an array, allowing us to define multiple Hooks.

Using a global variable

As we have learned, the value is stored within the closure that is defined by the useState function. Every time the component rerenders, the closure is reinitialized...

Comparing our reimplementation with real Hooks

Our simple Hook implementation already gives us an idea about how Hooks work internally. However, in reality, Hooks do not use global variables. Instead, they store state within the React component. They also deal with the Hook counter internally, so we do not need to manually reset the count in our function component. Furthermore, real Hooks automatically trigger rerenders of our component when the state changes. To be able to do this, however, Hooks need to be called from a React function component. React Hooks cannot be called outside of React, or inside React class components.

By reimplementing the useState Hook, we have learned a couple things:

  • Hooks are simply functions that access React features
  • Hooks deal with side effects that persist across rerenders
  • The order of Hook definitions matters

The last point is especially important...

Alternative Hook APIs

Sometimes, it would be nice to define Hooks conditionally or in loops, but why did the React team decide to implement Hooks like this? What are the alternatives? Let's go through a few of them.

Named Hooks

We could give each Hook a name and then store the Hooks in an object instead of an array. However, this would not make for a nice API, and we would also always have to think of coming up with unique names for Hooks:

// NOTE: Not the actual React Hook API
const [ name, setName ] = useState('nameHook', '')

Furthermore, what would happen when the conditional is set to false, or an item is removed from the loop? Would we clear the Hook state? If we do not clear the Hook state, we...

Solving common problems with Hooks

As we found out, implementing Hooks with the official API also has its own trade-offs and limitations. We are now going to learn how to overcome these common problems, which stem from the limitations of React Hooks.

We will take a look at solutions that can be used to overcome these two problems:

  • Solving conditional Hooks
  • Solving Hooks in loops

Solving conditional Hooks

So, how do we implement conditional Hooks? Instead of making the Hook conditional, we can always define the Hook and use it whenever we need it. If this is not an option, we need to split up our components, which is usually better anyway!

...

Solving problems with conditional Hooks

Now that we have learned about the different alternatives to conditional Hooks, we are going to solve the problem that we had in our small example project earlier. The simplest solution to this problem would be to always define the Hook, instead of conditionally defining it. In a simple project like this one, always defining the Hook makes the most sense.

Edit src/App.js and remove the following conditional Hook:

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

Replace it with a normal Hook, such as the following:

    const [ name, setName ] = useState('')

Now, our example works fine! In more complex cases, it might not be feasible to always define the Hook. In that case, we would need to create a new component, define the Hook there, and then conditionally render...

Summary

In this chapter, we started out by reimplementing the useState function, by making use of global state and closures. We then learned that in order to implement multiple Hooks, we need to use a state array instead. By using a state array, however, we were forced to keep the order of Hooks consistent across function calls. This limitation made conditional Hooks and Hooks in loops impossible. We then learned about possible alternatives to the Hook API, their trade-offs, and why the final API was chosen. Finally, we learned how to solve the common problems that stem from the limitations of Hooks. We now have a solid understanding of the inner workings and limitations of Hooks. Furthermore, we learned about the State Hook in depth.

In the next chapter, we are going to create a blog application using the State Hook, and learn how to combine multiple Hooks.

...

Questions

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

  1. What problems did we run into while developing our own reimplementation of the useState Hook? How did we solve these problems?
  2. Why are conditional Hooks not possible in the React implementation of Hooks?
  3. What are Hooks, and what do they deal with?
  4. What do we need to watch out for when using Hooks?
  5. What are the common problems of alternative API ideas for Hooks?
  6. How do we implement conditional Hooks?
  7. How do we implement Hooks in loops?

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 €14.99/month. Cancel anytime}