Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Designing React Hooks the Right Way

You're reading from   Designing React Hooks the Right Way Explore design techniques and solutions to debunk the myths about adopting states using React Hooks

Arrow left icon
Product type Paperback
Published in Jan 2022
Publisher Packt
ISBN-13 9781803235950
Length 278 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Fang Jin Fang Jin
Author Profile Icon Fang Jin
Fang Jin
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Chapter 1: Introducing the Function Component 2. Chapter 2: Crafting States in Functions FREE CHAPTER 3. Chapter 3: Hooking into React 4. Chapter 4: Use State to Jumpstart Components 5. Chapter 5: Use Effect to Handle Side Effects 6. Chapter 6: Use Memo to Boost Performance 7. Chapter 7: Use Context to Cover an Area 8. Chapter 8: Use Ref to Hide Stuff 9. Chapter 9: Use Custom Hooks to Reuse Logic 10. Chapter 10: Building a Website with React 11. Other Books You May Enjoy

Creating a good state solution

States are quite capable. A component without states is like a function without variables. It would lack capabilities of reasoning. A piece of UI logic relies on states to work upon continuous interactions from users.

We built a custom state in the previous chapter as follows:

let states = {}
function _getM2(initialValue, key) {
  if (states[key] === undefined) {
    states[key] = initialValue
  } 
  return states[key]
}
function _setM2(v, key) {
  states[key] = v
  ReactDOM.render(<Title />, rootEl)
}

Though this approach works, there are a few problems we need to address before we can be seriously considered using it with React. We'll mention these problems one by one as follows.

The location where the states are allocated is the first major problem:

let states = {}

The preceding states variable is allocated as a global variable, but normally we&apos...

lock icon The rest of the chapter is locked
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 $19.99/month. Cancel anytime
Banner background image