Home > Net >  How do I set only one element of a one dimensional array using useState in react js?
How do I set only one element of a one dimensional array using useState in react js?

Time:10-27

I want to set the value of an element of an array something like this

array_name[2] = true;

And also I want to access the value

console.log(array_name[2]);

But how do I do this using useState hook in react js? Does anyone know? Please tell.

CodePudding user response:

const [array, setArray] = React.useState([1, 2, 3]);
// ...
setArray(oldArray => {
   const newArray = [...oldArray];
   newArray[2] = true;
   return newArray;
});

is the most bulletproof way to do that I can think of. Using the function form of setState also avoids a dependency on array for effect/callback hooks using it.

CodePudding user response:

const [myArray, setMyArray] = useState(initialArray);

// later in your code
setMyArray(prev => {
  prev[2] = true;
  return [...prev]; // because you want updated state for anything watching for changes
});
  • Related