React Hooks: Array Destructuring Fundamentals

Published on : July 25,2022
React Hooks: Array Destructuring Fundamentals

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.

 

I'm a firm believer that:

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:

 

Can I call the values whatever I want?

// const [whateverIWant, reallyICanChooseWhatItIsCalled] = useState(0);
var _useState = useState(0),
  whateverIWant = _useState[0],
  reallyICanChooseWhatItIsCalled = _useState[1]

 

Can I add more elements?

// const [count, setCount, somethingElse] = useState(0);
var _useState = useState(0),
  count = _useState[0],
  setCount = _useState[1],
  somethingElse = _useState[2]

 

Can I pull out fewer?

// const [count] = useState(0);
var _useState = useState(0),
  count = _useState[0]

 

Can I skip one?

// const [, setCount] = useState(0);
var _useState = useState(0),
  setCount = _useState[1]

 

Can I skip more?

// const [,,, wow,, neat] = useState(0);
var _useState = useState(0),
  wow = _useState[3],
  neat = _useState[5]

 

I saw someone put a weird = 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.

  • Note: most of the things above you would never need to do with 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]

 

We can write:

const [count, setCount] = useState(0)

 

Thank You ! 

Categories : React

Tags : React Js

Praful Sangani
Praful Sangani
I'm a passionate full-stack developer with expertise in PHP, Laravel, Angular, React Js, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap. I enjoy sharing my knowledge by writing tutorials and providing tips to others in the industry. I prioritize consistency and hard work, and I always aim to improve my skills to keep up with the latest advancements. As the owner of Open Code Solution, I'm committed to providing high-quality services to help clients achieve their business goals.


174 Comments

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


betfair casino online buy stromectol 3mg ivermectin cream canada cost


buy symmetrel 100 mg sale buy amantadine 100mg without prescription dapsone 100 mg us


free online blackjack buy synthroid cheap synthroid 150mcg drug


clomiphene for sale cost clomiphene azathioprine 50mg without prescription


methylprednisolone pill how to get nifedipine without a prescription order aristocort pill


buy levitra 20mg pills order digoxin 250mg pills buy tizanidine online


perindopril 4mg cheap coversyl uk order fexofenadine 180mg online


dilantin 100 mg cost where to buy cyclobenzaprine without a prescription buy oxytrol for sale


buy lioresal no prescription order toradol 10mg toradol buy online


buy claritin paypal buy claritin 10mg for sale purchase priligy pills


baclofen pill cost ketorolac toradol generic


buy alendronate 35mg online colcrys 0.5mg generic purchase macrodantin for sale


glimepiride pill purchase amaryl without prescription buy arcoxia paypal


order inderal 10mg pills cheap motrin 600mg plavix brand


buy medex medication metoclopramide cheap order maxolon pill


buy generic orlistat 120mg orlistat online order purchase diltiazem pill


buy famotidine sale order cozaar 25mg online order prograf 5mg online


order azelastine 10ml nasal spray irbesartan 300mg without prescription buy generic avalide over the counter


order esomeprazole 20mg for sale topiramate 200mg cost buy topiramate pills


sumatriptan canada order dutasteride online order dutasteride sale


buy zyloprim 100mg for sale order allopurinol 300mg generic rosuvastatin drug


ranitidine over the counter order mobic 7.5mg for sale celebrex 100mg without prescription


buspar 10mg tablet ezetimibe order generic amiodarone 100mg


buy flomax 0.2mg generic cost simvastatin 20mg order simvastatin 10mg online


order domperidone 10mg generic carvedilol price buy sumycin 500mg generic


purchase spironolactone generic aldactone uk proscar 5mg ca


essay buy online purchase term paper help with papers


buy diflucan 200mg sale generic diflucan ciprofloxacin price


metronidazole 400mg ca buy generic cephalexin 500mg cephalexin drug


cost lamotrigine nemazole price buy cheap mebendazole


buy cleocin 150mg online cheap buy erythromycin sildenafil uk


tretinoin gel cheap buy avana 100mg generic avanafil 100mg uk


tamoxifen 20mg pills buy nolvadex 20mg pills purchase symbicort online


buy tadalafil 20mg generic buy tadacip 10mg pill buy indocin cheap


order cefuroxime generic purchase methocarbamol pills how to get robaxin without a prescription


buy trazodone pill buy clindamycin gel buy clindac a paypal


purchase lamisil online cheap order lamisil 250mg sale poker sites


cheap aspirin 75 mg online casino for real money casino slots


buy essay paper buy suprax 200mg generic order cefixime pill


help write my paper casino online slots online casino games


buy trimox 500mg online trimox 250mg sale generic biaxin


rocaltrol 0.25mg generic buy rocaltrol pills order tricor online cheap


oral clonidine 0.1 mg order tiotropium bromide 9 mcg buy tiotropium bromide 9mcg online cheap


permanent acne removal treatment trileptal order purchase trileptal for sale


buy cheap alfuzosin is claritin stronger than benadryl medicine for sharp stomach pain


order minocin pill hytrin 5mg sale order requip 2mg pill


best online rx for sleep medication induced baldness online prescriptions weight loss medication


buy generic femara for sale order femara 2.5mg online cheap aripiprazole 20mg sale


prescription meds for quitting smoking dangers of osteoporosis drugs buy painkillers without an rx


purchase provera online brand biltricide cost hydrochlorothiazide


name some antiviral drugs asthma inhalers non prescribed recent diabetic drug commercial


periactin medication how to get nizoral without a prescription buy nizoral generic


what causes fungus on skin medication to prevent herpes outbreaks foods that help lower blood pressure


buy cymbalta 20mg without prescription modafinil cost modafinil us


instant relief for stomach ulcer pain emergency high blood pressure medication gram negative bacteria in urine


buy generic phenergan online promethazine 25mg generic ivermectin 8000


cheap birth control pills online best anti inflammatory for prostate buy priligy 30mg online cheap


purchase deltasone pill accutane 40mg oral buy amoxicillin tablets


famotidine merck manual supplements that cause gerd causes of excessive smelly flatulence


azithromycin pills buy generic neurontin over the counter buy neurontin 100mg online


buy urso 300mg for sale actigall price buy generic cetirizine 5mg


buy strattera cheap purchase strattera pill buy sertraline 50mg for sale


lasix for sale online ventolin 2mg inhaler buy ventolin 2mg pills


escitalopram uk buy prozac pills revia pills


augmentin 625mg brand augmentin 1000mg us buy generic clomiphene 100mg


buy combivent online buy decadron 0,5 mg pills order zyvox 600 mg pill


starlix 120mg cost order generic starlix buy atacand pills for sale


starlix 120 mg generic cost capoten 120mg order candesartan for sale


buy levitra paypal cheap levitra 10mg order hydroxychloroquine


tegretol 400mg canada buy generic tegretol 400mg lincocin 500mg uk


order generic cenforce order metformin pills order metformin pill


order cefadroxil 250mg for sale ascorbic acid 500mg cheap where can i buy epivir


lipitor order buy zestril 2.5mg generic buy zestril online cheap


oral cabergoline 0.5mg cabergoline 0.25mg price buy dapoxetine pills for sale


depo-medrol where to buy methylprednisolone order online oral clarinex 5mg


purchase cytotec generic buy misoprostol 200mcg generic diltiazem for sale online


buy nootropil pills order generic piracetam 800mg order clomipramine 25mg


acyclovir 800mg cheap order acyclovir buy rosuvastatin 20mg generic


buy itraconazole no prescription itraconazole for sale online order tinidazole 500mg without prescription


ezetimibe us where can i buy motilium buy tetracycline pill


order olanzapine 10mg order olanzapine 10mg pill diovan oral


cyclobenzaprine 15mg tablet baclofen for sale toradol brand


order generic colchicine buy methotrexate online order generic methotrexate 2.5mg


prescription acne medications brand names order isotretinoin 40mg generic prescription medication for adult acne


behind the counter allergy medicine buy zaditor sale common prescription allergy pills


anti nausea medication during chemotherapy purchase quinapril sale



purchase deltasone without prescription buy prednisone 5mg pill


which anti anxiety drugs increase heartburn lincomycin 500 mg generic


how to clear adult acne buy prednisolone for sale acne medication by prescription


heartburn relief without calcium generic lincomycin 500 mg


accutane order order accutane 10mg sale accutane 40mg over the counter


Друзья нуждались в поддержке, и я решил подарить им цветы. "Цветов.ру" сделал этот процесс простым, а красочный букет точно придал им немного света в серых буднях. Советую! Вот ссылка https://extralogic.ru/stav/ - цветы букеты


online pharmacies sleeping pills provigil medication


cheap amoxicillin 250mg cheap amoxicillin 1000mg buy amoxicillin 500mg


azithromycin 500mg over the counter order zithromax generic zithromax us


buy gabapentin 600mg for sale cheap gabapentin generic


buy azipro 500mg for sale azithromycin 250mg price azipro for sale


furosemide online order buy furosemide generic diuretic


order omnacortil 40mg pills order omnacortil 20mg pill buy omnacortil 5mg without prescription


cost deltasone 20mg cost deltasone 40mg


amoxil cost buy amoxicillin 500mg sale amoxil usa


buy doxycycline without prescription order doxycycline 200mg


ventolin uk albuterol 2mg cheap albuterol inhalator without prescription


amoxiclav drug augmentin 625mg cost


cheap levoxyl pills purchase levoxyl pills order synthroid 75mcg online


vardenafil oral order levitra 10mg


clomid 100mg uk purchase clomiphene for sale order clomiphene 100mg generic


buy zanaflex pills buy zanaflex tablets tizanidine price


В моем стремлении к здоровому питанию, я нашел идеального помощника - https://blender-bs5.ru/collection/sokovyzhimalki-dlya-granata - выжималку для граната от 'все соки'. Это устройство стало неотъемлемой частью моего утра.


buy generic semaglutide over the counter cost rybelsus 14 mg cost rybelsus


order prednisone 20mg sale prednisone 20mg cheap order deltasone generic


semaglutide 14mg tablet buy rybelsus for sale rybelsus pill


oral isotretinoin 40mg purchase isotretinoin generic cost isotretinoin 40mg


purchase ventolin sale order generic albuterol order ventolin 2mg sale


amoxicillin 500mg for sale buy amoxil 500mg without prescription order generic amoxil


cheap augmentin 1000mg augmentin 375mg us purchase augmentin online


order azithromycin 500mg sale buy generic azithromycin over the counter azithromycin order


levothroid tablet buy synthroid without prescription levoxyl online


order generic prednisolone 5mg buy generic omnacortil online buy prednisolone 10mg for sale


casino money real online blackjack sports gambling


vardenafil price levitra over the counter buy vardenafil 10mg generic


oral lyrica order pregabalin 75mg pill pregabalin 150mg usa


buy hydroxychloroquine pill plaquenil buy online order hydroxychloroquine online cheap


triamcinolone price aristocort 10mg drug triamcinolone for sale


buy tadalafil online cialis us tadalafil 10mg tablet


clarinex online order clarinex pills order desloratadine 5mg online


cenforce cost order cenforce 50mg generic cenforce 50mg


order claritin sale buy loratadine paypal buy loratadine online


us pharmacy for cialis pharmaceuticals from canada us pharmacy cialis http://canadianphrmacy23.com/


chloroquine pills aralen 250mg ca buy chloroquine no prescription


purchase priligy generic priligy 30mg over the counter cytotec 200mcg tablet


oral orlistat 120mg orlistat 120mg canada order diltiazem for sale


purchase atorvastatin online buy generic lipitor lipitor 40mg over the counter


zovirax 400mg usa order allopurinol online cheap buy zyloprim pills for sale


norvasc 10mg uk buy norvasc 10mg sale how to buy norvasc


crestor pill generic crestor 20mg ezetimibe order


order zestril 2.5mg sale lisinopril 10mg canada buy lisinopril 5mg pill


canadian pharmacies viagra pharmacy canadian online pharmacy for cialis canada online pharmacy


order motilium 10mg pills domperidone brand sumycin pills


purchase omeprazole sale omeprazole oral purchase prilosec without prescription


buy flexeril pill buy lioresal online order baclofen 10mg generic


buy lopressor 100mg without prescription order metoprolol 50mg sale lopressor price


purchase toradol sale ketorolac pill where can i buy gloperba


buy cheap atenolol order atenolol 50mg generic order tenormin pills


Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles

Create Basic Login form with React JS Example
Praful Sangani By Praful Sangani - July 22,2022
Groups in React Textbox
Praful Sangani By Praful Sangani - August 03,2022