Hi Developer,
This article will learn about Hooks Array Destructuring Fundamentals in React.
For read mor about react hooks visit https://reactjs.org/hooks documentation
Let's see the example:
import {useState} from 'react'
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
That const [count, setCount] = useState(0);
is the line we're going to be talking about today. The syntax here is called "array destructuring" and it was introduced into JavaScript in the infamous (more than famous) ES6 release.
The better you understand an abstraction, the more effective you will be at using it. – me, literally right when I wrote this...
So when I see syntax that I'm unfamiliar with, I like to read about it and understand how it works with the rest of the language. The problem is that it can be difficult to "Google" syntax. Seriously... Try Googling the syntax itself as if you didn't know that it's called "destructuring." Pretty tough! So here's my trick. I go to astexplorer.net and paste in the code that I don't understand:
Cool! Babel calls that an "ArrayPattern." So let's go ahead and Google for that. We'll search for https://developer.mozilla.org array pattern" (that way Google only returns results for articles on MDN which is a terrific resource on learning everything there is to know about JavaScript).
Sweet, the first result takes us to "Destructuring assignment" where we can learn all about this feature (I guess you can read that instead of continuing here if you want to 😅).
Often syntax like this is what we call "syntactic sugar" for other features. Here's what wikipedia says about syntactic sugar:
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
Ok, so basically it means that there are common patterns or ways to write code in a given language, so the language makes a syntax feature to make that pattern require less code or more expressive. With this in mind, when I'm learning new syntax, I like to "de-sugar" the syntax to see what it would look like if we didn't have that feature.
Luckily for us, we have Babel and TypeScript which can compile this newer syntax into something older browsers can support (and presumably to something we may be more familiar with). So my next step is to go to the online babel REPL and paste in the code. Here's what the result looks like:
'use strict'
var _slicedToArray = (function () {
function sliceIterator(arr, i) {
var _arr = []
var _n = true
var _d = false
var _e = undefined
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value)
if (i && _arr.length === i) break
}
} catch (err) {
_d = true
_e = err
} finally {
try {
if (!_n && _i['return']) _i['return']()
} finally {
if (_d) throw _e
}
}
return _arr
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i)
} else {
throw new TypeError(
'Invalid attempt to destructure non-iterable instance',
)
}
}
})()
// const [count, setCount] = useState(0);
var _useState = useState(0),
_useState2 = _slicedToArray(_useState, 2),
count = _useState2[0],
setCount = _useState2[1]
😬 YIKES! Hmmm... Ok, so sometimes Babel uses utilities which both make it more compliant to the specification, but also can make the code a little harder to understand. Luckily, there's an option on the Babel Repl's "Env Preset" called "Loose" which will simplify this output considerably:
// const [count, setCount] = useState(0);
var _useState = useState(0),
count = _useState[0],
setCount = _useState[1]
😌 Phew, that's better. Ok, so what's going on here. Babel's taking our one line and rather than using the Array Pattern thing, it's assigning the return value of useState to a variable called _useState. Then it's treating _useState as an array and it assigns count to the first item in the array and setCount to the second one.
Let's play around with this a little bit to explore the syntax:
// const [whateverIWant, reallyICanChooseWhatItIsCalled] = useState(0);
var _useState = useState(0),
whateverIWant = _useState[0],
reallyICanChooseWhatItIsCalled = _useState[1]
// const [count, setCount, somethingElse] = useState(0);
var _useState = useState(0),
count = _useState[0],
setCount = _useState[1],
somethingElse = _useState[2]
// const [count] = useState(0);
var _useState = useState(0),
count = _useState[0]
// const [, setCount] = useState(0);
var _useState = useState(0),
setCount = _useState[1]
// const [,,, wow,, neat] = useState(0);
var _useState = useState(0),
wow = _useState[3],
neat = _useState[5]
=
sign in there, what does that do?// const [count = 3, setCount] = useState(0);
var _useState = useState(0),
_useState$ = _useState[0],
count = _useState$ === undefined ? 3 : _useState$,
setCount = _useState[1]
Oooh, fancy, so if the first element of the array is undefined, then we'll set count
to 3
instead. Default values! Sweet.
useState
because we can always rely on useState
returning an array of two elements! We'll look at that more next.Ok cool, so this helps us understand what's actually going on. There's nothing React-specific about this syntax. It's built-into the JavaScript specification, and React's useState
hook is leveraging it as a mechanism for an ergonomic API that allows you to get two values out of a single function call. Neat!
Ok, so what does useState
actually do then? What is it really returning? It must be returning an array for us to be doing the array destructuring like this right? Cool, let's check that out.
One thing that's interesting is that the implementation of useState
exists within react-dom
rather than react
. I know, that may be confusing because we import useState
from the react
package, but it actually just delegates to the current renderer (which is react-dom
in our situation here). In fact, setState
is the same way!
Another interesting thing about useState
is that the implementation in react-dom
is just a few lines:
function useState(initialState) {
return useReducer(
basicStateReducer,
// useReducer has a special case to support lazy useState initializers
initialState,
)
}
😱 it's actually just a hook that's using the useReducer
hook! Ok, but what is that basicStateReducer
thing huh?
function basicStateReducer(state, action) {
return typeof action === 'function' ? action(state) : action
}
Ok, interesting, so useReducer
is actually over 100 lines of code, so let's just look at what useReducer
returns:
return [newState, dispatch]
See! It's an array! So when we call useState
, it returns a call to useReducer
which will return an array of two values. This allows us to do the array destructuring that we want so instead of writing:
const stateAndUpdater = useState(0)
const count = stateAndUpdater[0]
const setCount = stateAndUpdater[1]
const [count, setCount] = useState(0)
Thank You !
Categories : React
Tags : React Js
buy fenofibrate online order tricor 160mg for sale buy fenofibrate 160mg online
cost tadalafil order cialis 5mg online cheap sildenafil 50mg canada
purchase ketotifen without prescription geodon cost buy tofranil generic
minoxidil over the counter buy cialis online cheap top ed drugs
aspirin over the counter eukroma buy online buy imiquimod sale
buy generic meloset norethindrone medication order generic danazol 100 mg
buy dipyridamole 100mg online dipyridamole 100mg brand brand pravachol 20mg
order duphaston sale purchase dydrogesterone online cheap jardiance 25mg cost
purchase florinef generic rabeprazole medication order loperamide 2 mg generic
etodolac us mebeverine 135 mg for sale order pletal 100mg online
buy prasugrel sale order generic chlorpromazine 100mg order detrol for sale
buy cheap generic pyridostigmine order feldene 20 mg generic rizatriptan brand
ferrous uk ascorbic acid 500mg over the counter pill betapace
buy vasotec 5mg order casodex 50mg sale buy lactulose online
where to buy xalatan without a prescription generic xeloda 500mg exelon 3mg drug
order betahistine 16mg pill order haldol 10 mg sale cost probenecid
premarin 0.625mg generic cabergoline online oral sildenafil 100mg
buy omeprazole 10mg generic montelukast 10mg sale lopressor 50mg generic
tadalafil 40mg ca real viagra viagra sildenafil 100mg
buy telmisartan 20mg generic purchase movfor online buy cheap molnupiravir
cenforce pill naproxen canada order chloroquine 250mg
provigil 200mg price order prednisone 5mg generic deltasone 20mg ca
omnicef 300 mg sale buy cefdinir pills for sale lansoprazole 15mg for sale
isotretinoin 40mg pills zithromax pills purchase zithromax for sale
azipro 250mg without prescription order omnacortil 40mg buy generic gabapentin for sale
order atorvastatin 10mg generic buy lipitor 40mg without prescription buy amlodipine generic
slots online casino online blackjack order lasix 100mg for sale
purchase pantoprazole pill order pantoprazole 20mg pills buy pyridium online
casino games real money ventolin 4mg usa ventolin inhalator for sale