[Reac] React 18

Replace Legacy Root API with New Root API

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

 

Use React 18's New Root API Alongside the Legacy Root API

Behavior of each type of API for React 17 and 18:

let root1 = document.getElementById("root");
let root2 = document.getElementById("root-2");

ReactDOM.createRoot(root1).render(<App root="18" />);
ReactDOM.render(<App root="17" />, root2)

 

Replace Legacy Root API's Callback Argument

React's legacy root API (render) took a callback function. React called this function once the post-render. With new streaming capabilities scheduled for React 18, this feature becomes unpredictable. Replace it with a ref callback — or one of these other strategies.

There are several ways to fix the previous warning. First one is by using useEffect

function App() {
   React.useEffect(() => console.log("React rendered"), [])
   return <div> Hello, React! </div>
}

we can also use callback function:

ReactDOM.createRoot(root).render(
   <App callback={(ref) => console.log(ref.tagName)} />
   );

function App({ callback }) {
   return <div ref={callback}> Hello, React! </div>
}

 

Conditionally Render with Legacy Root API or New Root API

const REACT_18 = true; 

if (REACT_18) {
   ReactDOM.createRoot(root).render(<App />);
} else {
   ReactDOM.render(<App />, root);
}

 

Opt-in to Automatic Batching with createRoot

In previous versions of React, state update batching only happened inside of event handlers. In React 18, all updates are batched, regardless of when or where they are called. Opt into automatic batching with createRoot.

复制代码
function App() {
    let [count, updateCount] = React.useState(1);
    let [isOdd, updateIsOdd] = React.useState(true);

    function handleClick() {
        setTimeout(() => {
            updateCount((count) => count + 1);
            updateIsOdd((oddness) => !oddness);
        }, 0);
    }

    console.count("re-rendered");

    return (
        <div>
            <button type="button" onClick={handleClick}>
                {count} {isOdd.toString()}
            </button>
        </div>
    );
}
复制代码

In v17, each time button was clicked, will console log two times. This is because we call the update function in setTimeout.

If we did following, then it only log once

    function handleClick() {
       updateCount((count) => count + 1);
       updateIsOdd((oddness) => !oddness);
    }

But in v18 the problem was solved.

 

Remove unstable_batchedUpdates Calls

React 17 exposes an undocumented API named unstable_batchedUpdates. It batches multiple useState update calls — inside of asynchronous callbacks — and reduces extraneous renders.

In React 18, all useState updates are batched, making unstable_batchedUpdates inert. Remove all uses of unstable_batchedUpdates.

 

Opt-out of Automatic Batching with ReactDOM.flushSync

In React 18, useState update calls are batched for improved performance. A new API — ReactDOM.flushSync — lets us selectively escape batching. This option is useful when reading the DOM after state changes. Use ReactDOM.flushSync to exempt specific state updates from batching.

ReactDOM.flushSync(() => {
    updateCount((count) => count + 1)
});
updateIsOdd((oddness) =>!oddness)

 

posted @   Zhentiw  阅读(174)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-12-21 [LeetCode] 832. Flipping an Image
2019-12-21 [LeetCode] 709. To Lower Case
2019-12-21 [LeetCode] 1221. Split a String in Balanced Strings
2019-12-21 [Algorithm] 1290. Convert Binary Number in a Linked List to Integer
2019-12-21 [LeetCode] 1281. Subtract the Product and Sum of Digits of an Integer
2018-12-21 [Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript
2017-12-21 [Python] Statistical analysis of time series
点击右上角即可分享
微信分享提示