DEV Community

Lumin
Lumin

Posted on

3 1

บันทึกความเข้าใจเรื่อง 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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up