Search code examples
javascriptreactjsreact-nativeimmutabilityimmutable.js

Question on Best practices: Immutability and re-rendering with React Native


I have created an immutable map and am currently using it with redux and i have some general questions about immutability. From what I understand, when passing props down to a component the props do an initial render. If the value of the prop is changed it doesn't re-render since Javascript is doing an === operation to check the address of memory rather than checking the values of that memory. What immutability does is change the address within memory to trigger the re-render. My concern right now is: aren't we wasting memory resources if I plan on never using the map that is in stored in the old address in memory. Also, if this is done repetitively with the user clicking on an immutable map expanding its memory usage more and more, couldn't this cause performance issues? Is there a way to remove the old address in memory after the new one is created? Here is some of my Redux code if you could give me pointers on if I am doing anything wrong:

import {Map} from 'immutable'
const likesAndSaved = new Map()

function likesAndSavedReducer(state = likesAndSaved, action) {
  switch (action.type) {
    case 'updateObj':
      return state.set(action.payloadId, action.payloadData)
  
  default:
    return state;
 }
}

Solution

  • Unreferenced objects are removed from memory by the garbage collector. That also applies to "the old value" in a Immutable.js Map.

    To cite the intro page of immutable-js.com:

    These data structures are highly efficient on modern JavaScript VMs by using structural sharing via hash maps tries and vector tries as popularized by Clojure and Scala, minimizing the need to copy or cache data.

    When you build a Map with 1000 entries, and then change a single one, this type of datastructure does not have to copy all these references and/or values. Instead it just has to extend a small part of the trie. So even if you kept a reference to both old and new state, the increase in memory usage would be minimal. When you clear the reference to one (e.g. the old) state, the javascript VM can clear that memory whenever it feels like doing so.

    You might even gain performance, because shallow checking properties with === is now enough to determine changes. You may now safely use use PureComponent. No need to deeply analyze objects in order to determine whether data has actually changed.

    Disclaimer: I am part of the maintainer team of Immutable.js and also a heavyily using it in large applications.