-
Notifications
You must be signed in to change notification settings - Fork 49.9k
Closed
Labels
Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugA potential issue that we haven't yet confirmed as a bug
Description
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
- Call
useOptimisticwith astatevariable - Update the value of
stateeither viasetStateor any other method that would cause a rerender - The initial
stateis returned as theoptimisticState

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.
markspolakovs, JesseKoldewijn, ilia-luk, 1-Felix, jazzypants1989 and 16 moreFredkiss3, danbeck79, magoz, Feel-ix-343, katerynarieznik and 3 more
Metadata
Metadata
Assignees
Labels
Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugA potential issue that we haven't yet confirmed as a bug