Skip to main content

React Asynchronous setState


setState is asynchronous action

- If you need to use the updated state to do something, you should use a callback function in setState, so it will call after the state is updated:

this.setState({data: newData}, () => console.log(this.state.data))

- If you wanna update the state with anything else, for example, set the '"title" to be "Hello", you can use the object in setState function, like this: this.setState({title: 'Hello'})

- But if you have to take the current state and use it to evaluate what to update, you should pass a function to setState function, so you will have access to the previous state and previous props. It will guarantees that you always get the latest update of the state or props:

this.setState((prevState, prevProps) => {
    return {count: prevState.count + 1}
  }
)

Comments

Popular posts from this blog

Arrow function lexical scoping

You can not bind arrow function They automatically get what called lexical scoping - which mean, they bind " this " context to the place where they were defined in the first place It's easier to write class method by using arrow function, so you can stop worry about bind " this "

Props vs State, Why?

Vì sao lại cần Props và State Khi người ta tạo ra các component, họ mới đặt câu hỏi làm sao để các component giao tiếp với nhau (từ parent tới child). Nên người ta mới nghĩ ra props (properties) để truyền data. Props là read-only , không thể thay đổi hay tác động (immutable) Nhưng khi một component cần react , render tùy theo tác động trực tiếp vào nó, nó cần data riêng để thể hiện sự thay đổi đó, nên người ta nghĩ ra sẽ cho component state (trạng thái) để thể hiện điều đó. State chỉ có thể update bởi chính component đó, bên ngoài không thể tác động

Recursion - Đệ quy là gì

"Recursion is when a function calls itself until it doesn't" Là một hàm gọi chính nó cho tới khi dừng. Vậy khi nào nó dừng? Khi nó thỏa điều kiện và không gọi chính nó nữa! (Duh? I'm I a joke to you) Vâng đúng là như vậy. Trong Recursion nó hai phần chính: - Base case: Trường hợp cơ bản - Tại case này, hàm sẽ không gọi lại chính nó nữa => Recursion sẽ dừng lại. - Recursive case: Trường hợp recursive - Như tên gọi, case này thì hàm sẽ tiếp tục gọi (recursive) chính nó tiếp. Ví dụ: Bằng bài toàn tìm giai thừa (factorial) function factorial(num) { if (num === 1 ) return 1 // Base case return num * factorial(num - 1 ) // Recursive case } console.log(factorial( 4 )) // 24 Để hiểu hơn, hãy xem Call stack của hàm trên: 4. factorial(1) | return 1 3. factorial(2) | return 2 * factorial(1) 2. factorial(3) | return 3 * factorial(2) 1. factorial(4) | return 4 * factorial(3) Như vậy sau khi hàm dừng recursive thì Call ...