0

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>
  );
}




webdev
  • 11
  • 2

2 Answers2

0

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

Konflex
  • 465
  • 3
  • 11
  • I understand what prevState is. I want to understand if it garbage collected automatically or not. The referenced answer helps in explaining the prevState not garbage collection. @Konflex – webdev Oct 06 '22 at 20:31
  • There is no garbage collection but just a variable you pass to the callback function. – Konflex Oct 06 '22 at 20:38
  • So every state update will create a new prevState in memory. If it is not garbage collected there will a lot of memory wastage. – webdev Oct 06 '22 at 20:42
0

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.

Optimix
  • 66
  • 4