import { useRef, useState } from "react";
import "./styles.css";
export default function App() {
const [array, setArray] = useState(["apple", "mango", "strawberry"]);
console.log("outside", array, Date.now());
function update(e) {
const name = document.getElementById("name").value;
const pos = Number(document.getElementById("pos").value);
setArray((prev) => {
console.log("prev ===>", prev, Date.now());
return [...prev, (prev[pos] = name)];
});
}
const inputRef = useRef();
const posRef = useRef();
return (
<div className="App">
<input id="name" ref={inputRef} placeholder="fruit name" />
<input id="pos" ref={posRef} placeholder="posistion" />
<div style={{ display: "flex", justifyContent: "center", gap: "25px" }}>
<div>
{array.map((info, index) => (
<p key={index}>{info}</p>
))}
</div>
</div>
<button onClick={update}>UPDATE</button>
</div>
);
}
for the first update new fruit is appending at the end but from 2nd update onwards new fruit is appenidng at the end plus its replacng at the position also. and moreover console.log also confusing especially the prev===> one it is not logging the recent fruit state
note: i knw it isn not right way of updating the array im just trying to understand the behaviour.
react app is in STRICT MODE
2
Answers
Here’s the updated code,try this once :
I got your question and analyzed it. Here is my analysis…
First question why it is not logging inside setArray?
First of all useState is async method. So that, your set state changes won’t update immediately, That’s why it cannot log your array values at real time.
if suppose you want to show those changes you can use ‘useEffect’ to get the updated value after ‘array’ updated. Like following code snippet…, you can keep the code out of your ‘update’ method
above code can show updated value after "array" is updated.
now coming to second point why that value is replacing the first index?
The answer is same as first one. state is async. So, First it will update the value on the position as per your request on below line
(prev[pos] = name) –> this thing updates first, on the position you requested. if you set 1 at the position input it will set at first index then it appends the data at end. if it is 2 then second index. Especially the () this braces doing main role. If there is no braces it don’t update the first indexes, rather it only do append on the array.
Please upvote if you got my answer… Thanks.