aryan singh
aryan singh

Reputation: 424

useState array destructuring react

I always see this type of code:

const [value, setValue] = useState(null);

since value can be changed using setValue, why are we using const for value.

Upvotes: 2

Views: 211

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

What const means is that the value for that identifier in that scope cannot be reassigned. You can't do

const x = 5;
x = 6;

or

function foo(arg) {
  const theArg = arg;
  theArg = 5;
}

But there's nothing stopping you from running the function again, resulting in a new binding for that variable:

function foo(arg) {
  const theArg = arg;
}
foo(5);
foo(6);

The above is what React is doing - it runs the whole function component again, which results in useState returning the updated state. No const identifier ever gets reassigned.

Another example:

let i = 0;
const useState = () => [i, newI => { i = newI; TheComponent(); }];

const TheComponent = () => {
  const [i, setI] = useState();
  console.log('component running with i of', i);
  setTimeout(() => {
    setI(i + 1);
  }, 1000);
};

TheComponent();

Upvotes: 5

Related Questions