Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Principle Analysis of State in React

2025-01-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the principle analysis of State in React, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Question: is setState synchronous or asynchronous?

If you have some understanding of the underlying layer of React, you can answer the concept of batchUpdate batch updates and the conditions under which batch updates are broken.

Answer: sometimes synchronous, sometimes asynchronous.

Asynchronous in composite events and lifecycle functions, synchronous in native events and setTimeout, promise

The asynchronism of setState is not caused by internal asynchronous code, and is synchronized during its own execution, but the calling order of composite events and lifecycle functions is before the update, so that the updated value can not be directly obtained internally, which can be obtained with the second parameter callback.

Specific explanation: you can refer to the implementation process of setState

Class component state

SetState (obj,callback)

The first parameter: when obj is an object, it is the state to be merged; if obj is a function, then the state and props of the current component will be used as parameters, and the return value will be used to merge the new state.

The second parameter callback: callback is a function. You can get the value of the latest state after the current setState update in the function execution context. It can be used as a side effect function that depends on state changes and can be used to do some DOM-based operations.

The above setState is triggered once in an event to execute the process at the bottom of the React:

Render phase render function execution-> commit phase real DOM replacement-> setState callback function executes callback

First, setState produces the priority of the current update (the old version uses expirationTime and the new version uses lane). Next, the React will downgrade the fiber from the root of the fiber Root to the child nodes, and the reconciliation phase will update the expirationTime where the update occurs, find the component where the update occurs, merge the state, and then trigger the render function to get a new UI view layer to complete the render phase. Then come to the commit phase, commit phase, replace the real DOM, and complete the update process. At this point, it is still in the commit phase, and the callback function in setState is executed, and the whole setState process is completed at this point.

Uncover the secret of setState principle

Essence: the underlying React calls the enqueueSetState method on the Updater object

EnqueueSetState (): create a update, put it in the queue of the current fiber object to be updated, and finally start scheduling updates to enter the update process.

BatchUpdate batch updates for React

Purpose: multiple setstate will make the logic stay at the running level of js, blocking browser rendering, so batch updates are needed.

BatchedEventUpdates ():

Analysis process:

Before the execution of the React event, turn on the switch through isBatchingEventUpdates=true to enable the batch update of the event.

When the event is over, turn off the switch through isBatchingEventUpdates=false

Use this switch in scheduleUpdateOnFiber to determine whether to update in batches

1) in asynchronous environment, continue to enable batch update mode:

The batch update rule in the asynchronous operation will be broken, so a manual batch update method is provided: unstable_batchedUpdates

2) raise the update priority:

A method is provided: flushSync, which can give priority to the update task in the callback function.

Add: flushSync will merge the previous setState under synchronization condition | useState

3) Summary: the priority relationship of React updates at the same level is:

SetState in flushSync > normal execution context setState > Asynchronous setTimeout, setState in Promise

Function component state

Const [state, dispatch] = useState (initData)

The ① state purpose is provided to UI as a data source for rendered views

② dispatch changes the function of state, which can be understood as a rendering function that promotes the rendering of function components.

③ initData initial value

Initial value of initData

The first case is a non-function, which will be the value initialized by state

The second case is the function, where the return value of the function is used as the value initialized by useState.

Parameters of dispatch

The first non-functional case, which will be assigned to state as a new value for the next rendering

The second is the case of a function. If the parameter of dispatch is a function, it can be called reducer,reducer parameter, which returns the latest state last time, and returns the value as the new state.

Listen for state changes

UseEffect: you can often pass state as a dependency to deps, the second parameter of useEffect, but note that useEffect initialization is performed once by default

Features of dispatch update

It is the same as the class component, but when calling the function dispatch that changes the state, you cannot get the latest state value in the context of this function execution.

Reason: the update of the function component is the execution of the function. During one execution, all variables within the function are redeclared, so the changed state is updated only the next time the function is executed.

UseState principle will be explained by Hooks later.

Q: what are the similarities and differences between setState in class components and useState in function components?

Answer: the same point:

Principle: setState and useState update the view, the bottom layer calls the scheduleUpdateOnFiber method, and there are batch update rules in event-driven cases

Syntax: the first parameter can be passed into the function

Differences:

In non-pureComponent component mode, setState does not compare the value of state twice. Whenever setState is called, the update is performed. But dispatchAction in useState will update the component by default by comparing whether the state is the same twice.

SetState has a callback function callback that specifically listens for state changes, which can obtain the latest state. But useState can only perform the side effects caused by state changes through useEffect.

SetState merges the old state in the underlying processing logic, while useState reassigns the value

Thank you for reading this article carefully. I hope the article "Analysis of the principles of State in React" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report