1

I changed only const value... but, Why output is Hello? Please explain it...

import React, { useState } from "react";

export default function App() {
    const [value, setValue] = useState(["hi"]);

    const handlePress = () => {
        console.log(value);
        const a = value;
        a[0] = "Hello";
    };

    return (
        <div className="App">
            <button onClick={handlePress}>Press</button>
        </div>
    );
}
  • 1
    When you declare `const a = value;` it doesn't copies your `value` array, it simply holds a reference to your array. So any modification you do to `a` happens to `value` and vice-versa. – brc-dd Jul 19 '21 at 18:09
  • 1
    Does this answer your question? [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/q/29050004/11613622), [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/q/6612385/11613622). PS: In JS arrays are objects. – brc-dd Jul 19 '21 at 18:10
  • Also, if you are surprised that you can modify a state variable without setState function, then make yourself conformable that indeed you can do so, but it is not recommended, and may even don't work in certain scenarios. [Why can't I directly modify a component's state, really?](https://stackoverflow.com/q/37755997/11613622) – brc-dd Jul 19 '21 at 18:17

1 Answers1

1

Because you are initalizing a state value to be an array which is call by reference so if you directly overide the value then the actual value will be overriden state won't be update , so to update an array you can create a new array and assign value or use spread operation .

import React, { useState ,useEffect} from "react";

export default function App() {
    const [value, setValue] = useState(["hi"]);

    const handlePress = () => {
        // array are pass by reference so , value reference is passed to a variable and the first element is over riden by value "Hello"
        const a = value;
        a[0] = "Hello";
    };

   useEffect(()=>{
   console.log(value,"check how value changes here")
   },[value])

    return (
        <div className="App">
            <button onClick={handlePress}>Press</button>
        </div>
    );
}

Goutham J.M
  • 1,726
  • 12
  • 25