Skip to content

Bug: Stale values returned from useOptimistic when state changes #27617

@dorshinar

Description

@dorshinar

The optimisticState returned from useOptimistic is stale when the state param passed to useOptimistic is changed. The change could come from an RSC reponse or from a setState.

React version: 18.2.0

Steps To Reproduce

  1. Call useOptimistic with a state variable
  2. Update the value of state either via setState or any other method that would cause a rerender
  3. The initial state is returned as the optimisticState
    image

Link to code example: https://github.com/dorshinar/next-optimistic-bug

I've recreated the bug in a Next project, but the important component is this:

export function Form() {
  const [arrFromServer, setArrFromServer] = useState([1, 2, 3]);

  useEffect(() => {
    const interval = setInterval(() => {
      setArrFromServer((a) => [...a, a.length + 1]);
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, []);

  const [optimisticArr] = useOptimistic(arrFromServer, (s) => s);
  console.log("🚀 ~ arrFromServer:", arrFromServer);
  console.log("🚀 ~ optimisticArr:", optimisticArr);

  return <div>{JSON.stringify(optimisticArr)}</div>;
}

The current behavior

When there is no form submission in progress, the optimisticArr always returns the initial state provided to it.

The expected behavior

I'd exepct that optimisticState returned from useOptimistic to be in sync with the state param passed to it.

Metadata

Metadata

Assignees

Labels

Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions