skip to Main Content
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

image after first update

image after second update

2

Answers


  1. Here’s the updated code,try this once :

    import { useRef, useState } from "react";
    import "./styles.css";
    
    export default function App() {
      const [array, setArray] = useState(["apple", "mango", "strawberry"]);
    
      function update(e) {
        const name = inputRef.current.value;
        const pos = Number(posRef.current.value);
    
        setArray((prev) => {
          const newArray = [...prev]; // it create a new array to avoid mutating state directly
          if (pos >= 0 && pos < prev.length) {
            newArray[pos] = name; // Replace at the specified position
          } else {
            newArray.push(name); // Append at the end if the position is invalid
          }
          console.log("newArray ===>", newArray, Date.now());
          return newArray;
        });
      }
    
      const inputRef = useRef();
      const posRef = useRef();
    
      return (
        <div className="App">
          <input id="name" ref={inputRef} placeholder="fruit name" />
          <input id="pos" ref={posRef} placeholder="position" />
          <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>
      );
    }
    
    Login or Signup to reply.
  2. 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

    useEffect(() => {console.log(array)},[array])
    

    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

    return [...prev, (prev[pos] = name)];
    

    (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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search