I find this
App.tsx
import './App.css'
import useHome from './hooks/useHome'
function App() {
useHome();
return <div></div>
}
export default App
src/hooks/useHome.ts
import { useEffect, useState } from "react";
const query = (): Promise<number> =>
new Promise((resolve) =>
setTimeout(() => {
resolve(1);
}, 1000),
);
const useHome = () => {
const [pageStatus, setPageStatus] = useState<string>("loading");
const [data, setData] = useState<number | null>(null);
const [deps, setDeps] = useState(data);
const queryData = async () => {
setPageStatus("loading");
try {
const pageData = await query();
setData(pageData); // cause second @render
setPageStatus("normal"); // cause third @render
} catch (e) {
setPageStatus("error");
}
};
useEffect(() => {
queryData();
}, []);
useEffect(() => {
setDeps(data); // cause third @render
}, [data]);
useEffect(()=> {
console.log('@batch'); // only console 2 times. why react batch update setPageStatus and setDeps ?
}, [pageStatus, deps]);
console.log("@render"); // total 3 times
return {
deps,
data,
pageStatus,
};
};
export default useHome;
In react 17 , because of this async function, setData(pageData) and setPageStatus(‘normal’) won’t batch update . It’s meets my expectations. (of cuz its will do batch update in React18)
But i find that setPageStatus(‘normal’) and setDeps(data) batch update together.
Can anyone tell me why? It would be best to have documentation. I didn’t find a corresponding explanation on the official website.
WangYuanFuRong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.