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 because it means that we cannot conditionally define Hooks. We should always have all the Hook definitions at the beginning of our function component, and never nest them within if or other constructs.

Here we have also learned the following:

  • React Hooks need to be called inside React function components
  • React Hooks cannot be defined conditionally, or in loops

We are now going to look at alternative Hook APIs that allow conditional Hooks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.210