Reputation: 3289
I'm trying to figure out how to get state variables to update. To test, I made the simplest possible app and tried every method I could think of to update state variables - simple variables, arrays, and objects. To my surprise, the setState
functions failed in every case except for updating an individual item in a state array using an arrow function. See my code below:
import { useState, useEffect } from 'react'
function App() {
const [myInt, setMyInt] = useState(0)
const [myArr, setMyArr] = useState([])
const [myObj, setMyObj] = useState({att1: "", att2: ""})
//REGULAR VARIABLES
setMyInt(5); //myInt = 0, DOESN'T WORK
setMyInt((prev) => 10); //myInt = 0, DOESN'T WORK
const newInt = 15;
setMyInt(newInt); //myInt = 0, DOESN'T WORK
useEffect(() => { //never gets run, DOESN'T WORK
setMyInt(20);
}, []);
useEffect(() => { //never gets run, DOESN'T WORK
setMyInt((prev) => 25);
}, []);
//increment
setMyInt(myInt + 1); //myInt = 0, DOESN'T WORK
setMyInt((prev) => prev + 1); //myInt = 0, DOESN'T WORK
useEffect(() => { //never gets run, DOESN'T WORK
setMyInt((prev) => prev + 1);
}, []);
//NO WAY TO UPDATE REGULAR STATE VARIABLE. USE SIMPLE VARIABLE INSTEAD.
var myInt2 = 0;
myInt2 = 30; //myInt2 = 30, WORKS
myInt2 = myInt2 + 1; //myInt2 = 31, WORKS
//ARRAYS
setMyArr([1, 2]); //myArr = [], DOESN'T WORK
setMyArr((prev) => [3, 4]); //myArr = [], DOESN'T WORK
const newArr = [5, 6];
setMyArr(newArr); //myArr = [], DOESN'T WORK
//update specific value
myArr[0] = 7; //myArr = [7], WORKS
setMyArr((prev) => prev, myArr[0] = 8); //myArr = [8], WORKS
const newArr2 = [...myArr];
newArr2[0] = 9;
setMyArr(newArr2); //myArr = [8], DOESN'T WORK
setMyArr((prev) => newArr2); //myArr = [8], DOESN'T WORK
useEffect(() => { //never gets run, DOESN'T WORK
const newArr3 = [...myArr];
newArr3[0] = 10;
setMyArr(newArr3);
setMyArr((prev) => newArr3);
}, []);
//NO WAY TO UPDATE AN ENTIRE ARRAY; CAN ONLY UPDATE INDIVDUAL ELEMENTS
//OBJECTS
setMyObj({ att1: "a", att2: "b" }); //myObj = {"", ""}, DOESN'T WORK
setMyObj((prev) => ({ att1: "c", att2: "d" })); //myObj = {"", ""}, DOESN'T WORK
const newObj = {att1: "e", att2: "f"};
setMyObj(newObj); //myObj = {"", ""}, DOESN'T WORK
//update specific value
myObj.att1 = "g"; //myObj = {"g", ""}, WORKS
setMyObj((prev) => ({ prev, att1: "h" })); //myObj = {"g", ""}, DOESN'T WORK
const newObj2 = { ...myObj };
newObj2.att1 = "i";
setMyObj(newObj2); //myObj = {"g", ""}, DOESN'T WORK
setMyObj((prev) => newObj2); //myObj = {"g", ""}, DOESN'T WORK
useEffect(() => { //never gets run, DOESN'T WORK
const newObj3 = {...myObj};
newObj3.att1 = "j";
setMyObj(newObj3);
setMyObj((prev) => newObj3);
}, []);
//NO WAY TO UPDATE A STATE OBJECT; CAN ONLY UPDATE INDIVDUAL ATTRIBUTES
return (
<>
</>
);
}
export default App
Upvotes: -3
Views: 33