React hook - useEffect - run useEffect only once

- Truyền 1 function làm tham số thứ nhất của
useEffect - Truyền 1 mảng rỗng làm tham số thứ hai của
useEffect - Function ở tham số thứ nhất sẽ chỉ gọi đúng 1 lần duy nhất.
- Tương đương
componentDidMounttrong class.
Ví dụ:
- Tạo biến count = 0
- Khi render lần đầu tiên thì document title hiển thị: You click 0 times
- Khi click vào button thì count + 1
- Mặc dù click nhiều lần nhưng document title không thay đổi.
// HookCounter.js
import { useState, useEffect } from 'react'
export default function HookCounter() {
const [count, setCount] = useState(0)
useEffect(() => {
document.title = `You click ${count} times`
}, [])
return (
<button onClick={() => setCount(count + 1)}>
Click {count} times
</button>
)
}
Viết code lại tương đương với componentDidMount trong class
// ClassCounter.js
import { Component } from 'react'
export default class ClassCounter extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
componentDidMount() {
document.title = `You click ${this.state.count} times`
}
render() {
const { count } = this.state
return (
<button onClick={() => this.setState({ count: count + 1 })}>
Click {count} times
</button>
)
}
}
