skip to Main Content

I was going through this code by atlassian on how to use pragmatic-drag-and-drop in codesanbox.

There they have used

const [registry] = useState(getItemRegistry);

    // Isolated instances of this component from one another
const [instanceId] = useState(() => Symbol('instance-id'));

Trying to understand, what’s the use of using state, without ever being able to setState? like they don’t have const [registry, setRegistry] = useState(getItemRegistry);. Couldn’t this be useMemo instead?

Sandbox link

2

Answers


  1. I think useState is used here to guarantee that the values are initialized once per component and remain stable across renders. I mean useMemo could work, but it might be recalculated, and it doesn’t really match "immutable state."

    Login or Signup to reply.
  2. Couldn’t this be useMemo instead?

    useMemo() should be used for performance optimisations only (see docs). React doesn’t make any promises that the cached value will always be retained with useMemo(), so using it for a stable reference across renders isn’t necessarily guaranteed with useMemo():

    however, since useMemo is performance optimization, not a semantic guarantee, React may throw away the cached value if there is a specific reason to do that

    That’s why using the original useState() variable is more reliable to get a stable reference across renders, which is what you need with Symbols (as each new symbol created is unique), and is also suggested in the React docs as an alternative (my emphasis):

    for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should be fine if you rely on useMemo solely as a performance optimization. Otherwise, a state variable or a ref may be more appropriate

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search