[React] Force React to update it's DOM by using flushSync
Refer to https://react.dev/reference/react-dom/flushSync
For example, the browser onbeforeprint
API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use flushSync
inside of the onbeforeprint
callback to immediately “flush” the React state to the DOM. Then, by the time the print dialog opens, isPrinting
displays “yes”:
Without flushSync
, the print dialog will display isPrinting
as “no”. This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated.
import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
export default function PrintApp() {
const [isPrinting, setIsPrinting] = useState(false);
useEffect(() => {
function handleBeforePrint() {
flushSync(() => {
setIsPrinting(true);
})
}
function handleAfterPrint() {
setIsPrinting(false);
}
window.addEventListener('beforeprint', handleBeforePrint);
window.addEventListener('afterprint', handleAfterPrint);
return () => {
window.removeEventListener('beforeprint', handleBeforePrint);
window.removeEventListener('afterprint', handleAfterPrint);
}
}, []);
return (
<>
<h1>isPrinting: {isPrinting ? 'yes' : 'no'}</h1>
<button onClick={() => window.print()}>
Print
</button>
</>
);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-07-31 [Functional Programming] Make a flip and reverse functions
2021-07-31 [SAA + SAP] 13. S3
2020-07-31 [XState] History state
2020-07-31 [XState] Nested State
2018-07-31 [Angular] New in V6.1
2018-07-31 [Javascript] JavaScript赋值时的传值与传址
2017-07-31 [React Intl] Use Webpack to Conditionally Include an Intl Polyfill for Older Browsers