"variable" is read only

Viewed 802

I have the following code and I am getting error of "count" is read-only:

import React, {useState} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';

const CounterScreen = () => {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Button onPress={() => setCount(count++)} title="Increase" />
      <Button onPress={() => setCount(count--)} title="Decrease" />
      <Text>Current Counter: {count}</Text>
    </View>
  );
};

const styles = StyleSheet.create({});
export default CounterScreen;

But if I use setCount(count + 1) instead of setCount(count++), it works perfectly. What is the difference here between count + 1 and count++

4 Answers

The important thing to remember is that you can change the value of a variable declared as a const, but you cannot reassign it. Here is a good blog post about this:

https://mathiasbynens.be/notes/es6-const

setCount(count+1) is taking the current value of the variable count, adding 1 to it and then passing this to our setter function, 'setCount' to update our state. We are in no way reassigning the 'count' variable. React is updating the value of 'count' under the hood using the setter function.

What you are doing with count++ is attempting to re-assign the count variable, not just change the value of the 'count' variable.

count++ is shorthand for count = count + 1; you are actually changing the value of a variable. not just reading its value.

count++ is similar as count = count + 1 means it's changing the variable itself and you know const are read-only after initialization that is why you doing setCount() to update the value.

and count + 1 is not updating itself.

const [count, setCount] = useState(0);

Your count in here ↑ is read only, if you want to change it's value have to call setCount()

Like setCount(num)

so if num= 10 then equal to setCount(10)

So that setCount(count + 1) could work, count+1 is a number

But why setCount(count++) couldn't work is because

count++

Equal to

count=count+1; //It is changing the value of count directly!
setCount(count++) 

setCount(count=count+1) //So count++ is changing the value of count directly, not through setCount, couldn't work.

It couldn't work and may error for "count" is read-only

This is try to change count value without calling setCount in setCount

Related