惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How React Updates State
Dmitri Pavlutin · 2020-12-15 · via Dmitri Pavlutin Blog

React useState() hook manages the state in functional React components. In class components this.state holds the state, and you invoke the special method this.setState() to update the state.

Mostly using state in React is straightforward. However, there's an important nuance to be aware of when updating the state.

When you update the component's state, does React update the state immediately (synchronously) or rather schedules a state update (asynchronously)? This post answers this question.

1. State update using useState()

Consider a functional component DoubleIncreaser:


import { useState } from 'react';

function DoubleIncreaser() {

const [count, setCount] = useState(0);

const doubleIncreaseHandler = () => {

setCount(count + 1);

setCount(count + 1);

};

return (

<>

<button onClick={doubleIncreaseHandler}>

Double Increase

</button>

<div>Count: {count}</div>

</>

);

}


const [count, setCount] = useState(0) defines the component state. count is the state variable containing the current state value, while setCount() is the state updater function.

The component has a button Double Increase. When the button is clicked, doubleIncreaseHandler event handler performs 2 consecutive increments of count state: setCount(count + 1) and then setCount(count + 1) again.

When clicking Double Increase, does the component's state update by 1 or 2?

Open the demo and click the button Double Increase. The count is increased by 1 on each click.

When setCount(count + 1) updates the state, the changes are not reflected immediately in the count variable. Rather React schedules a state update, and during the next rendering in the statement const [count, setCount] = useState(0) the hook assigns to count the new state value.

For instance: if count variable is 0, then calling setCount(count + 1); setCount(count + 1); is simply evaluated as setCount(0 + 1); setCount(0 + 1); — making the state on next render as 1.

The state update function setValue(newValue) of [value, setValue] = useState() updates the state asynchronously.

The state update function also accepts a callback to compute new state using the current state. In case of the DoubleIncreaser, you can use setCount(actualCount => actualCount + 1):


import { useState } from 'react';

function DoubleIncreaser() {

const [count, setCount] = useState(0);

const doubleIncreaseHandler = () => {

setCount(actualCount => actualCount + 1);

setCount(actualCount => actualCount + 1);

};

return (

<>

<button onClick={doubleIncreaseHandler}>

Double Increase

</button>

<div>Count: {count}</div>

</>

);

}


When updating the state using a function setCount(actualCount => actualCount + 1), then actualCount argument contains the actual value of the state.

Open the demo, and click the Double Increase button. The count updates by 2 as expected.

Of course, you can use an intermediate let variable:


import { useState } from 'react';

function DoubleIncreaser() {

const [count, setCount] = useState(0);

const doubleIncrease = () => {

let actualCount = count;

actualCount = actualCount + 1;

actualCount = actualCount + 1;

setCount(actualCount);

};

return (

<>

<button onClick={this.doubleIncrease}>

Double Increase

</button>

<div>Count: {count}</div>

</>

);

}


let actualCount = count is an intermediate variable that you can update at will. The updated intermediate variable to update the setCount(actualCount).

Try the demo using intermediate variable.

2. The state variable is immutable and readonly

If you forget that the state variable updates on the next rendering, you might try to read the state variable right after changing it. Unfortunately, it won't work:


function FetchUsers() {

const [users, setUsers] = useState([]);

useEffect(() => {

const startFetching = async () => {

const response = await fetch('/users');

const fetchedUsers = await response.json();

setUsers(fetchedUsers);

console.log(users); // => []

console.log(fetchedUsers); // => ['John', 'Mike', 'Denis']

};

startFetching();

}, []);

return (

<ul>

{users.map(user => <li>{user}</li>)}

</ul>

);

}


FetchUsers component starts a fetch request on mounting — startFetching().

When fetch is completed, setUsers(fetchedUsers) updates the state with the fetched users. However, the changes aren't reflected right away in users state variable.

The state variable users is readonly and immutable. Only useState() hook assigns values to users. You're not allowed manually to assign to state variable, neither mutate it:


function FetchUsers() {

const [users, setUsers] = useState([]);

useEffect(() => {

const startFetching = async () => {

const response = await fetch('/users');

const fetchedUsers = await response.json();

users = fetchedUsers; // Incorrect! users is readonly

users.push(..fetchedUsers); // Incorrect! users is immutable

setUsers(fetchedUsers); // Correct!

};

startFetching();

}, []);

return (

<ul>

{users.map(user => <li>{user}</li>)}

</ul>

);

}


3. State update in a class component

The same idea of the asynchronous state update is valid for class components too.

The following class component has a state count, which should increase by 2 when the button Double Increase is clicked:


import { Component } from 'react';

class DoubleIncreaser extends Component {

state = {

count: 0

};

render() {

return (

<>

<button onClick={this.doubleIncrease}>

Double Increase

</button>

<div>Count: {this.state.count}</div>

</>

);

}

doubleIncrease = () => {

// Works!

this.setState(({ count }) => ({

count: count + 1

}));

this.setState(({ count }) => ({

count: count + 1

}));

// Won't work!

// this.setState({ count: this.state.count + 1 });

// this.setState({ count: this.state.count + 1 });

}

}


Take a look at the doubleIncrease() event handler: the state updater also uses a callback.

Open the demo and click the button Double Increase. As expected, the this.state.count updates by 2.

In class based components, this.state is also not updated immediately. When calling this.setState(newState), React schedules a re-render, and exactly on next rendering this.state contains the new state value newState.

this.setState(newState) updates this.state asynchronously.

4. Summary

useState() hook and this.setState() (inside class components) update the state variable and the component output asynchronously.

Remember the simple rule:

Calling the setter function setValue(newValue) of useState() hook (or this.setState() of class components) doesn't exactly update the state, but rather schedules a state update.

Quiz: are references (created by useRef()) updated synchronously or asynchronously? Write the answer in a comment below!