Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use React18 status batch

Shulou Source: shulou.com Published: 2022-05-31 18:30:20 09月29日 Update

This article introduces the knowledge of "how to use React18 status batch". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Automatic batch processing of status

Prior to version 18, in native events other than synthetic events (such as setTimeout, onclick, promise), status updates were not batch processed (merged), which meant that multiple calls to status updates in native events resulted in re-rendering of multiple applications, often only the last time. React optimized this problem after version 18.

Import {useState} from 'react' function App () {const [num1, setNum1] = useState (1) const [num2, setNum2] = useState (1) const add = () = > {setTimeout (()) = > {setNum1 ((pre) = > pre + 1) setNum2 ((pre) = > pre + 1)} console.log (' rendered') return (react 18)

Num1: {num1}

Num2: {num2}

+ 1)} export default App17 version

After four clicks, the component rendered 8 times

Version 18

After 4 clicks, the component rendered 4 times

Automatic batch processing of exit status

In some scenarios, we may not need batch status updates, so we need to use the flushSync function provided by react-dom, which passes in a callback and refreshes the status updates in the callback synchronously.

Import {useState} from 'react'import {flushSync} from' react-dom' function App () {const [num1, setNum1] = useState (1) const [num2 SetNum2] = useState (1) const add = () = > {setTimeout (()) = > {flushSync (()) = > {setNum1 ((pre) = > pre + 1)}) flushSync (() = > {setNum2 ((pre) = > pre + 1)})} console.log ('rendered') console.log (num1, num2) return (react 18

Num1: {num1}

Num2: {num2}

+ 1)} export default App

Summary of main points

1. Status updates within native events are changed to batch processing

two。 When batch processing is not required, use the flushSync function provided by react-dom, which synchronously refreshes the status updates in the parameter callback

That's all for the content of "how to use React18 status batch". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: State update event function processing content more version knowledge component utility learning next parameters dilemma scenario actual situation meaning article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei NVidia Shulou Tech Info MariaDB vpn