Home > Net >  How is previous State garbage collected in React JS
How is previous State garbage collected in React JS

Time:10-07

As far as I understand react keeps track of prevState, when state is updated. Then how is the memory garbage collected for prevState? Is it garbage collected automatically when a new state is set. Or it still holds the memory for prevState?

export default function App() {
  const arr = Array.from({ length: 5 }, () => Math.floor(Math.random() * 5));
  const [myState, setMyState] = useState(arr);
  const handleClick = () => {
    setMyState([]);

    // Will this automatically de-allocate memory for the last state array?
    // OR
    // Will the prevState array will still be in memory heap. 
    // If yes, how to de-allocate this memory!
  };

  return (
    <div className="App">
      <button onClick={() => handleClick()}>Clear Array</button>
    </div>
  );
}




CodePudding user response:

What is prevState in ReactJS?

An answer from another poste that may help you. prevState is just the name of the variable you use to hold the previous state, to be able to update correctly your state in some case (rougthly way to say it).

CodePudding user response:

prevState should be a reference pointing to the state before the change.

But even if it would be duplicated, the garbage collector would free the memory after setting the new state if not referenced anymore.

  • Related