Book Image

Learn React Hooks

By : Daniel Bugl
Book Image

Learn React Hooks

By: Daniel Bugl

Overview of this book

React Hooks revolutionize how you manage state and effects in your web applications. They enable you to build simple and concise React.js applications, along with helping you avoid using wrapper components in your applications, making it easy to refactor code. This React book starts by introducing you to React Hooks. You will then get to grips with building a complex UI in React while keeping the code simple and extensible. Next, you will quickly move on to building your first applications with React Hooks. In the next few chapters, the book delves into various Hooks, including the State and Effect Hooks. After covering State Hooks and understanding how to use them, you will focus on the capabilities of Effect Hooks for adding advanced functionality to React apps. You will later explore the Suspense and Context APIs and how they can be used with Hooks. Toward the concluding chapters, you will learn how to integrate Redux and MobX with React Hooks. Finally, the book will help you develop the skill of migrating your existing React class components, and Redux and MobX web applications to Hooks. By the end of this book, you will be well-versed in building your own custom Hooks and effectively refactoring your React applications.
Table of Contents (19 chapters)
Free Chapter
1
Section 1: Introduction to Hooks
5
Section 2: Understanding Hooks in Depth
13
Section 3: Integration and Migration

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...