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
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."
useMemo()
should be used for performance optimisations only (see docs). React doesn’t make any promises that the cached value will always be retained withuseMemo()
, so using it for a stable reference across renders isn’t necessarily guaranteed withuseMemo()
:That’s why using the original
useState()
variable is more reliable to get a stable reference across renders, which is what you need withSymbol
s (as each new symbol created is unique), and is also suggested in the React docs as an alternative (my emphasis):