DEV Community

Teerasak Vichadee
Teerasak Vichadee

Posted on

บันทึกความเข้าใจเรื่อง React.useEffect

  • เราใช้ useEffect ใน React functional component แทน componentDidMount
  • useEffect คล้ายๆ componentDidMount แต่ไม่เหมือนซะทีเดียว และยืดหยุ่นกว่า
  • componentDidMount ถูก trigger ทุกครั้งที่ component ถูก mount กับ DOM หรือทุกครั้งที่ state เปลี่ยนแปลง
  • useEffect ก็จะ trigger ทุกครั้งที่ state หรือ props ของ function เปลี่ยนแปลง แต่เราสามารถกำหนดได้ด้วย ว่าจะสนใจ state หรือ props ไหน
  • นอกจากนั้นใน useEffect เองก็สามารถทำ componentWillUnMount ได้ด้วย โดย return function
  • useEffect เหมาะสำหรับเอาไปใช้รอรับ callback จาก ajax หรือทำ redux dispatch

ท่าในการใช้ useEffect

const component = () => {
  // state loaded เอาไว้ render ในกรณีที่ยังไม่ได้ข้อมูลจาก ajax (เช่น loading ก็ได้นะ)
  [loaded, setLoaded] = React.useState(false)
  // state content เอาไว้ใส่ข้อมูล
  [content, setContent] = React.useState('')

  useEffect(() => {
    // ดึงข้อมูลเสร็จแล้วค่อยทำ setContent
    getContent.then(res => {
      setLoaded(true)
      setContent(res)
    })

    // เมื่อทำ unmount ก็ clear state กลับเป็นอย่างเดิม
    return () => {
      setLoaded(false)
      setContent('')
    }
  }, 
  // state ที่เราสนใจจะ subscribe ใน useEffect ตัวนี้
  [loaded, content])
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)