Search code examples
javascriptreactjsreact-hooksgarbage-collection

garbage collection in javascript and react js


As I know javascript has its own garbage collection system. In react, when a functional component (which a function is kind of an object in javascript) gets updated, a new one is created and the old one will be passed away, unlike a class based component(correct me if I'm wrong!). So if a functional component has a ref object(using useRef) and passes that object to its parent component, every time it gets updated, the previous function component version cant be removed by GC because it has a ref somewhere in its parent component. I think, there is something wrong in my conclusion but I don't know for sure! I would appreciate your help if you can tell where is my mistake (if any).


Solution

  • So if a functional component has a ref object(using useRef) and passes that object to its parent component, every time it gets updated, the previous function component version cant be removed by GC because it has a ref somewhere in its parent component.

    The useRef hook stores the ref, so that the previous function component can be garbage collected. When a function component is re-rendered all the hooks are saved from the previous render.