Uploaded image for project: 'Realm JavaScript SDK'
  1. Realm JavaScript SDK
  2. RJS-1691

useObject will return referentially different objects for the same object

      How frequently does the bug occur?

      All the time

      Description

      Given the immutability conventions of react you would expect that

      Unable to find source-code formatter for language: jsx. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      const object = useObject('foo', 0)
      const object2 = useObject('foo', 0)
      assert(object === object2)
      

      However this is not the case.

      Referential equality is commonplace for the equivalent of useObject in all the most common state libraries such as redux, mobx and zustand. It's very common to use hooks instead of prop drilling and therefore natural to use useObject multiple times for the same object. This issue could produce potential gotchas for users such as unnecessary re-renders.

      One solution would be to maintain an object cache, each object would only have a single realm listener. The cache entry would track the number of active hooks there are for the object via list of plain JS listener callbacks. When the component unmounts the listener would be removed from the list of listeners. When the list of listeners drops to 0 the cache entry would be purged.

      This model would likely have some other benefits

      • Reduce the overhead of a new useObject as a new realm object instance and listener wouldn't have to be made if it was already in the cache
      • Less potential gotchas with creating listeners e.g. #4375

      A similar approach could be applied to useQuery

      Stacktrace & log output

      No response

      Can you reproduce the bug?

      Yes, always

      Reproduction Steps

      No response

      Version

      main

      What SDK flavour are you using?

      Local Database only

      Are you using encryption?

      No, not using encryption

      Platform OS and version(s)

      ios

      Build environment

      Which debugger for React Native: ..

      Cocoapods version

      No response

            Assignee:
            andrew.meyer@mongodb.com Andrew Meyer
            Reporter:
            unitosyncbot Unito Sync Bot
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: