why the component used useAtom will render twice when it has mounted. #1444
-
I'm sure I have turn off the StrictMode of react18. As you can see in the print message, the component I've read issue#1137 and edit the demo code by author. import { useState, useEffect } from "react";
import { atom, useAtom } from "jotai";
const msgAtom = atom("msg");
const Input = () => {
//Print once
console.log("Input render");
const [text, setText] = useState("hello");
const handleChange = (e) => setText(e.target.value);
return <input value={text} onChange={handleChange} />;
};
const Uppercase = () => {
const [msg] = useAtom(msgAtom);
//Print twice if i use useAtom
console.log("msg", msg);
console.log("uppercase render");
const [uppercase] = useState("HELLO");
useEffect(() => {
//Print once
console.log("uppercase Effect");
});
return <div>Uppercase: {uppercase}</div>;
};
export default function App() {
//Print once without strict mode
console.log("rerender....");
return (
<>
<Input />
<Uppercase />
</>
);
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It's the design choice to compute derived atoms in render phase, so that we let React schedule it. (And, also allow Suspense.) When you have a heavy computation, this behavior is a little troublesome. In such cases, heavy computations should be wrapped with fwiw, this is an expected behavior of |
Beta Was this translation helpful? Give feedback.
It's the design choice to compute derived atoms in render phase, so that we let React schedule it. (And, also allow Suspense.)
This leads to run render phase twice; first when invalidated, and second when the value is updated. Usually, the second time "bails out", so there's only one commit phase. (On second thought, this case is one render, which bails out without commits.)
When you have a heavy computation, this behavior is a little troublesome. In such cases, heavy computations should be wrapped with
useMemo
. This is a technique not specific to Jotai.fwiw, this is an expected behavior of
useReducer
in React 18 and Jotai intentionally uses thisuseReducer
behavior.