useEffect not always run when using useAtomValue and a hook using requestAnimationFrame #2541
Unanswered
timreinke
asked this question in
Bug report
Replies: 1 comment 1 reply
-
It's not directly related to Jotai but can be reproduced with React itself, if we use a function Example() {
const ref = React.useRef(null);
const refValue = ref.current;
const [, rerender] = React.useState({});
const [, dispatch] = React.useReducer(reducer, initial);
React.useEffect(() => {
ref.current = "foo";
const x = setTimeout(() => rerender({}), 1_000);
return () => clearTimeout(x);
}, []);
// Remove this and it works fine.
React.useEffect(() => dispatch(), []);
React.useEffect(() => console.log("useEffect", refValue), [refValue]);
console.log("render", refValue);
return <></>;
} Repro: https://codesandbox.io/p/devbox/react-dispatch-effect-yvj5f4 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This is a bit of a weird one I ran into when using
tiptap
. I isolated the behavior and reproduced with only react + jotai.In the example code,
useRefWithInitialization
is similar totiptap
'suseEditor
- it has a ref to hold onto an object instance. The ref starts offnull
, and is initialized in auseEffect
. TheuseEffect
and forces a rerender inside arequestAnimationFrame
.However, the
useEffect
is not re-run when usinguseAtomValue
.Example code:
The example code produces this log trace:
As you can see, the
UseAtomValue
component is properly rerendered afteruseRefWithInitialization
does its thing. But, the effect is not rerun with the new value.Deps:
Some interesting points to note:
useSetAtom
. It only breaks withuseAtomValue
useState
also works fineSandbox (includes components using
useSetAtom
anduseState
):https://codesandbox.io/p/devbox/vite-react-forked-thktkt?file=%2Fsrc%2Fmain.jsx%3A10%2C1-11%2C1&workspaceId=cb54fff1-7c30-47a6-b51e-4cc1f3702699
Beta Was this translation helpful? Give feedback.
All reactions