Why React doesn’t update state immediately | How React performs state updates | React Tutorial

Опубликовано: 15 Январь 2022
на канале: CodeWithKB
6,887
101

#react #reactjs #hook

Why React doesn’t update the state immediately?
Despite React’s popularity, one of its biggest drawbacks is its components re-rendering excessively. When developing React applications, you may have noticed that state updates don’t immediately reflect new values after being changed. React state is a plain JavaScript object that holds information that influences the output of a render.

When building your project, if you intend to alter any attributes of a React component in the future, you should store the attribute in a state. The state starts with an initial default value on mount and is then altered later on as a result of a user’s actions. Each React component manages its own state internally.

In this article, we’ll explore the reasons why React doesn’t update state immediately. We’ll run through an example and clarify what you should do when you need to make changes to the new state in both class and function components. Let’s get started!

How React performs state updates
To update state in React components, we’ll use either the this.setState function or the updater function returned by the React.useState() Hook in class and function components, respectively.

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass