Programming

The Result of getSnapshot Should Be Cached: A React Error That Looks Like an Infinite Render

React reports an infinite-loop warning even though no effect updates state. The actual problem may be a getSnapshot function that creates a new object every time it is called.

You connect a React component to an external store. The component only reads a value and displays it on the page. There is no setState() inside the render function, no useEffect updating anything, and no obvious reason for the component to render repeatedly.

Yet React reports:

Warning: The result of getSnapshot should be cached
to avoid an infinite loop

Sometimes the warning is followed by another error:

Maximum update depth exceeded.

The second message makes the situation more confusing. An infinite update loop usually suggests that something keeps changing state. But what if the store hasn’t changed at all?

Consider this example:

import { useSyncExternalStore } from "react";

const store = {
  count: 0
};

function subscribe() {
  return () => {};
}

function getSnapshot() {
  return {
    count: store.count
  };
}

export default function Counter() {
  const snapshot = useSyncExternalStore(
    subscribe,
    getSnapshot
  );

  return <p>Count: {snapshot.count}</p>;
}

The store contains one number. getSnapshot() reads it, wraps it in an object, and returns that object.

At first glance, there is nothing suspicious.

But the problem is precisely that new object.

Every time React calls getSnapshot(), the function creates another object, even when store.count has not changed.

And for useSyncExternalStore, that difference matters.

Why React needs the same snapshot twice

useSyncExternalStore allows a component to read data maintained outside React.

That data could come from a state-management library, a browser API, or a custom store shared with other parts of an application.

The Hook receives two main functions:

const snapshot = useSyncExternalStore(
  subscribe,
  getSnapshot
);

subscribe tells React how to listen for changes.

getSnapshot tells React what the current store value is.

React uses the returned snapshot to determine whether the component needs to render again.

But how does React know that something changed?

It compares the new snapshot with the previous one using Object.is().

Consider two calls:

const first = getSnapshot();
const second = getSnapshot();

console.log(Object.is(first, second));

With our original implementation, the result is:

false

Why?

Because these two objects are not the same object:

{ count: 0 }
{ count: 0 }

Their contents are identical, but JavaScript created two separate references.

React does not perform a deep comparison of their properties.

As far as the comparison is concerned, the snapshot has changed.

React may then attempt another render or perform another consistency check, only to receive yet another object.

function getSnapshot() {
  return { count: store.count };
}

Nothing needs to change in the store for this function to keep returning different references.

This violates the contract expected by useSyncExternalStore.

The warning is therefore not saying that React detected a normal state update that happened too frequently.

It is saying that React cannot obtain a stable representation of the store’s current state.

There is an important difference between those two situations.

Returning an existing immutable value

The simplest solution depends on how the external store is implemented.

Suppose the store already contains an immutable state object.

Instead of creating another object inside getSnapshot(), return that state directly.

import { useSyncExternalStore } from "react";

let state = {
  count: 0
};

const listeners = new Set();

function subscribe(listener) {
  listeners.add(listener);

  return () => {
    listeners.delete(listener);
  };
}

function getSnapshot() {
  return state;
}

function increment() {
  state = {
    ...state,
    count: state.count + 1
  };

  listeners.forEach((listener) => listener());
}

export default function Counter() {
  const { count } = useSyncExternalStore(
    subscribe,
    getSnapshot
  );

  return (
    <button onClick={increment}>
      Count: {count}
    </button>
  );
}

Now the store holds the snapshot itself.

Calling getSnapshot() repeatedly returns the same reference:

const first = getSnapshot();
const second = getSnapshot();

console.log(Object.is(first, second));
// true

When increment() runs, it creates a new state object and replaces the previous one.

Only then does getSnapshot() return a different reference.

The store also notifies its subscribers, allowing React to check the new snapshot.

The relationship is straightforward:

  • No state change: return the existing object.
  • State change: create a new state object and notify subscribers.

This example uses immutable updates by convention. The state should not be modified directly elsewhere.

If another part of the application executes:

state.count++;

the snapshot reference remains unchanged.

React may then fail to detect the update because Object.is(previousSnapshot, currentSnapshot) still returns true.

So returning an existing object is correct only when the store manages changes consistently.

The snapshot must be treated as immutable.

What if the external store is mutable?

Not every external store uses immutable updates.

Perhaps a third-party library modifies its internal objects directly. Or perhaps the application maintains mutable data for reasons unrelated to React.

In that case, returning the underlying object is not necessarily safe.

Consider:

const store = {
  count: 0
};

function getSnapshot() {
  return store;
}

If the store later changes:

store.count = 1;

the reference remains identical.

React cannot determine from Object.is() that the object’s contents changed.

We have therefore encountered the opposite problem.

Previously, getSnapshot() always returned a new object, even when nothing changed.

Now it always returns the same object, even when something does change.

Neither behavior correctly represents the store.

For mutable data, React recommends returning an immutable snapshot and caching it until the underlying data changes.

One possible implementation uses an explicit version number:

const store = {
  count: 0,
  version: 0
};

const listeners = new Set();

let cachedVersion = -1;
let cachedSnapshot = null;

function subscribe(listener) {
  listeners.add(listener);

  return () => listeners.delete(listener);
}

function getSnapshot() {
  if (cachedVersion !== store.version) {
    cachedSnapshot = Object.freeze({
      count: store.count
    });

    cachedVersion = store.version;
  }

  return cachedSnapshot;
}

function increment() {
  store.count++;
  store.version++;

  listeners.forEach((listener) => listener());
}

The internal store remains mutable.

But getSnapshot() does not create another object every time it is called.

It checks whether the store’s version changed.

If the version is unchanged, the function returns the previous snapshot.

If the version changed, it creates and caches a new immutable representation.

Now:

const first = getSnapshot();
const second = getSnapshot();

console.log(Object.is(first, second));
// true

After increment():

const third = getSnapshot();

console.log(Object.is(first, third));
// false

This is what React needs.

There is a condition behind the example, however.

Every meaningful mutation must update the version and notify subscribers.

If another function modifies store.count without updating store.version, the cached snapshot becomes stale.

For nested data, creating an immutable snapshot may also require copying nested objects or arrays rather than merely freezing the outer object.

The implementation must match the actual structure and mutation rules of the store.

When a primitive snapshot is enough

There is another possibility that can make the entire caching problem disappear.

Suppose the component only needs a number.

Why return an object at all?

Instead of:

function getSnapshot() {
  return {
    count: store.count
  };
}

Return the value directly:

function getSnapshot() {
  return store.count;
}

Now repeated calls return the same primitive value while the count remains unchanged.

Object.is(0, 0);
// true

If the count changes from zero to one, the comparison detects it.

Object.is(0, 1);
// false

There is no object identity to manage.

This is useful when a component only needs a particular primitive value from a store, such as a connection status, counter, or selected identifier.

For example, React’s documentation demonstrates useSyncExternalStore with navigator.onLine, which returns a boolean.

The result is naturally stable as long as the browser’s reported connection status does not change.

Of course, not every component can reduce its required snapshot to one primitive.

If several related values must be read together, an immutable object snapshot may be more appropriate.

But before introducing a caching mechanism, consider what the component actually needs.

Sometimes the simplest snapshot is already available.

Why useMemo does not necessarily fix this

After encountering the warning, it may be tempting to wrap getSnapshot in useCallback.

For example:

const getSnapshot = useCallback(() => {
  return {
    count: store.count
  };
}, []);

The function reference is now stable between renders.

But what happens when it is called twice?

Object.is(getSnapshot(), getSnapshot());
// false

The function still creates a new object each time.

Memoizing the callback does not automatically memoize its return value.

That is the distinction.

React requires a stable snapshot result while the store is unchanged, not merely a stable function reference.

Wrapping an object in useMemo somewhere inside the component can also miss the real issue if getSnapshot() continues producing fresh objects whenever React invokes it.

The correct place to address this is in the store’s snapshot implementation.

If the store already exposes immutable state, return it.

If it stores mutable data, cache a derived immutable snapshot and invalidate it when the underlying data changes.

The snapshot must accurately represent the store’s state across calls, independently of whether a particular component happened to render.

A different problem: subscribe changes on every render

There is another warning sign worth distinguishing.

Suppose subscribe is defined inside the component:

function Counter() {
  function subscribe(listener) {
    return store.subscribe(listener);
  }

  const count = useSyncExternalStore(
    subscribe,
    getSnapshot
  );

  return <p>{count}</p>;
}

Every render creates a new subscribe function.

React may therefore unsubscribe and subscribe again because the supplied function reference changed.

This can create unnecessary work.

But it is not the same as returning a new snapshot object on every call.

A straightforward improvement is to define subscribe outside the component when it does not need component-specific values.

function subscribe(listener) {
  return store.subscribe(listener);
}

This gives React a stable subscription function.

Still, if getSnapshot() returns a newly constructed object every time, stabilizing subscribe will not resolve the original warning.

The two functions serve different purposes, and their identities matter for different reasons.

What to check when the warning appears

When React reports that the result of getSnapshot should be cached, begin by examining the function’s return value.

Does it contain an object literal?

return { count: store.count };

An array created during the call?

return [...store.items];

Or perhaps a transformation that constructs a new result every time?

return store.items.map((item) => ({
  id: item.id,
  name: item.name
}));

All three can return new references even when the underlying data is unchanged.

A simple diagnostic is to call the function twice without modifying the store:

const first = getSnapshot();
const second = getSnapshot();

console.log(Object.is(first, second));

If the result is false, investigate why.

For an unchanged store, that generally violates the stability requirement.

Then check the other side of the contract.

After a real store update, does getSnapshot() return a different value representing the new state?

If the store is mutable, does its cache become invalid when data changes?

And does the store notify subscribers when an update occurs?

A correct external-store integration must handle both directions.

It should not invent changes when nothing happened.

It should not conceal changes that actually happened.

Why the warning describes an infinite loop

Return to the original implementation:

function getSnapshot() {
  return {
    count: store.count
  };
}

The count might remain zero forever.

But each call produces another object.

React compares the result with the previous snapshot and sees a difference.

After rendering, another snapshot check may produce yet another different object.

React can continue attempting to bring the rendered component into agreement with what appears to be a continuously changing external store.

Eventually, the runtime may report the unstable snapshot or an excessive update depth.

The misleading part is that no meaningful application data has changed.

There may not even be a store notification involved.

The problem is that getSnapshot() cannot give React a consistent answer to the same question.

What is the store’s current state?

For an unchanged store, the answer should remain the same.

Not merely an object with equivalent contents, but the same snapshot value according to Object.is().

Once that guarantee is established, React can distinguish a real external update from another read of existing data.

And in most cases, the fix does not require rewriting the component.

It requires correcting how the store exposes its state.

External Sources used for this article

Related Articles

View all →