-
-
Notifications
You must be signed in to change notification settings - Fork 622
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changing atom in useAtom returns previous atom's value once before returning the new atom's value #827
Comments
Interestingly this works correctly in terms of the Although, if you change from: useEffect(() => {
console.log("Atom index:", index, "Atom value", atomValue);
}, [atomValue]); to
you can see that it actually causes two re-renders (I am not sure whether I am lacking understanding of a fundamental react/jotai concept that explains this behavior) |
Thanks for reporting. That said, at this point, we are not sure if this is fixable, or how it behaves in React 18. Let me label as |
@Aslemammad Are you interesting in investigating this issue? |
Let's put it in my TODO list! |
Let me write my report here about what I've found. The updates weren't synced with the effects, so I tried to synchronize them using the #761 solution, and synchronization worked. Even though the issue wasn't non-synced renders (maybe it's part of the issue), the problem is more about scheduling. Lines 60 to 62 in 759ee14
As you can see, forceUpdate schedules the update (queue.pending), so the next render can consume it using useReducer. This makes the issue expected, but it'd be good to provide a solution (or point out that this is an issue in React itself, which there's not a high chance in this one). I'd like to hear your thoughts. |
This is interesting. It feels like a bug in useReducer, because the first click works expected (one commit), but the second click causes dual commits. tested with #841 tests. That said, even if it's a bug in useReducer, we'd want to fix the problem with the current version. I will add a commit to #841 for a workaround. |
It turns out that there was a misunderstanding of mine. I thought changing the reducer reference results in the re-evaluation, but how it behaves seems correct. So, #841 is not a workaround, but a correct solution. |
Description
When changing the atom used in a
useAtom
the return value will be once the previous atom value (updating the component etc), before changing to the new atom's value. So it causes two re-renders instead of one.Reproduction
A full reproduction can be seen here: https://codesandbox.io/s/jotai-useatom-issue-uo0uc?file=/src/App.js
The important code part looks like this:
As you can see, while the
currentAtomIndex
has already been changed, the atom's value on the first "run" isn't.Screen.Recording.2021-11-09.at.12.49.50.PM.mov
The text was updated successfully, but these errors were encountered: