Home > Software design >  How do array equals useState declarations work in Javascript?
How do array equals useState declarations work in Javascript?

Time:12-06

In functional components within ReactJS, the following line allows the creation of:

  1. A variable to record the current count
  2. A method to save the state when called

Example in JS:

let [count, setCount] = useState([]);

How does this work from a declaration point of view and what is this kind of declaration called?

I understand basic declarations like let array = []; etc but am not familiar with the other way around.

CodePudding user response:

When you are using useState in reactJS. It will return an array of two values

  1. A variable to record the current count.
  2. A method to save the state when called.

So you can either get the value individually using index as:

let arr = useState([]);

const count = arr[0];
const setCount = arr[1];

or you can also use destructuring as:

let [count, setCount] = useState([]);

Below is example of how destructure works

function customUseState(initialValue) {
  let val = initialValue;
  function changeVal(newVal) {
    val = newVal
  }
  return [val, changeVal];
}

// This is how destructure works
const [count, setCount] = customUseState(0);

CodePudding user response:

Usestate returns an array with two elements first is the value or state in your case "count" and second is function used to update the state in your case "setCount". Here you are not declaring them you are destructuring them. Its same like we do object destructuring.

{name,age}={obj} we are destructuring name and age from the obj same way you are extracting count and setCount from usestate. And array destructuing depends on the position of elements rather than variable names whereas in object destructuring it depends on variable names.

  • Related