AceDevHub
Advanced React Interview QuestionsAdvancedScenario

React · Question 85

What bugs occur if getSnapshot in useSyncExternalStore returns a new object every time?

Direct answer

If getSnapshot always returns a new reference even when the store has not changed, React can repeatedly treat the snapshot as changed and enter unnecessary or even infinite re-rendering.

store.js
function getSnapshot() {
  // Wrong: a fresh object every call.
  return {
    todos: store.todos
  };
}
  • Stable when unchanged: repeated reads must return the same value while the store has not changed.
  • Immutable snapshot: if the underlying store mutates objects, cache an immutable snapshot and only replace it after a real change.
  • SSR: getServerSnapshot must produce data that matches the initial client hydration snapshot.