Search code examples
reactjsreact-hookssetstate

Change variable from usestate other variable is getting reset in functional component


When I'm updating my state variable, so my state variable is changed, but my all other variables are getting resting to their initial values. I am adding my test component.

If I remove setTest so my combileFileData gives value as expected after pressing add button, but when I use setTest so everytime it gives me ['b]

  const [pass, setPass] = React.useState([]);
  let combineFileData = ["b"];

  function showHandler() {
    console.log("combine file data", combineFileData);
  }

  function addHandler() {
    setPass(["a", "s"]);

    combineFileData.push("a");
  }
  return (
    <div>
      <button onClick={showHandler}>Show</button>
      <button onClick={addHandler}>Add</button>
    </div>
  );
}

Solution

  • Your combineFileData is “reinitialized” on every render. There fore it behaves like it has its initial value always.

    To keep your inplementation as much same as possible you can use ref like this:

    const combineFileData = useRef([“b”]);
    
    function addHandler() {
        setPass(["a", "s"]);
    
        combineFileData.current.push("a");
    }