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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay