Home > Software engineering >  Change the state directly when using a useState
Change the state directly when using a useState

Time:12-27

I'm new to React native and I'm experimenting to understand some things. Below I can update the state with onPress1. When I press onPress2 I get a "read-only" error. But in onPress3 it doesn't give an error even though it updates the status directly. It changes the whole state in onPress2 and onPress3. If state was a variable, changing it directly would cause a "read-only" error. Why doesn't it give an error when I change only the first element or all elements of an object one by one? Also, to replace only 1 element of an existing array, is it okay if I directly replace only 1 element, similar to onPress3?

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

let data = [
  { word: "Strong" },
  { word: "Support" }
]

export default function WordSelect() {

  const [list, setList] = useState(data)

  const onPress1 = () => {
    setList([
      { word: "Together" },
      { word: "Drunk" }
    ])
  }

  const onPress2 = () => {
    list = [
      { word: "Together" },
      { word: "Drunk" }
    ]
  }

  const onPress3 = () => {
    list[0] = {  word: "Together" }
    list[1] = {  word: "Drunk" }
  }

  return (
    <View style={{paddingTop:50}}>
      <Button title='onPress1' onPress={()=>{onPress1()}}></Button>
      <Button title='onPress1' onPress={()=>{onPress2()}}></Button>
      <Button title='onPress1' onPress={()=>{onPress3()}}></Button>
      <Text>{list[0].word} </Text>
      <Text>{list[1].word} </Text>
    </View>
  )
}

CodePudding user response:

list is a const so doing list = something will throw an error, that's why onPress2 crashes.

onPress3 doesnt throw an error because you are not reassigning list itself. Doing :

const a = {b:1}
a.b = 2

is fine and will update a.b.

Note that you should always use setList to update your list. Only onPress1 has a correct syntax.

CodePudding user response:

As per ReactJS documentation you can only change the value of state by using the call back function that is setList in provided code. So basically you have to mutate the value of state via the function setList.

Please [click here][1] for more clarification.

  • Related