เขียน Code ให้กระชับขึ้น ด้วย React Hook

Pakinnatorn Boo
te<h @TDG
Published in
2 min readJun 3, 2020

เปลี่ยนจาก Class component เป็น functional

จากการท่ีหลายๆคน ได้ใช้ react เป็นเครื่องมือในการสร้าง webpage ของเราขึ้นมา อาจจะพบปัญหา Class component ของเรามีขนาดใหญ่ logic ใน Lifecycle ซ้ำซ้อนระหว่าง component logic ตีกัน ทำงานซ้ำหลายๆที บางทีอาจจะติด loop ต้องมาเพิ่ม logic ให้ไม่ทำงานซ้ำซ้อนอีก เสียเวลาไปกันใหญ่

class component แบบ ปกติ

Lifecycle Class component

parent => componentWillMount

child => componentWillMount

child => componentDidMount

parent => componentDidMount

Hook จึงเกิดมาเพื่อแก้ปัญหานี้

ตัวอย่างแรก useState

useState จะ return ค่าออกเป็น array 2 ตำแหน่ง ตำแหน่งแรกเป็นชื่อ state ตำแหน่งที่สองเป็น funtion

useState จะต้องใช้ภายใน function Component

แบบมีหลาย State

ถ้าต้องการ set value setCount(count + 1) get value ก็ {count} แบบนี้ได้เลยครับ

ตัวอย่างที่สอง useEffect

useEffect เป็น function จะรับ argument เป็น function เข้ามา

useEffect จะทำงานหลัง render ครั้งแรก แล้วก็จะทำงานอีกครั้งเมื่อมีการ update state หรือจะทำงานตาม function componentDidMount() componentWillMount() componentWillUpdate()

ในตัวอย่างนี้เวลา count ถูก update ก็จะมี side Effect ไปถึง document.title

useEffect(() => {
document.title = `You clicked ${count} times`;
};

ในตัวอย่างนี้จะทำการ setState ใน function useEffect จนทำให้ติด loop

useEffect(() => {
setCount(count + 1)
console.log('# useEffect ==>','')
});

เราควรเติม emty Array [ ] เป็น argument ตัวที่สองเข้าไป เพื่อให้ทำงานแค่ function componentDidMount() และ componentWillUnmount()

useEffect(() => {
setCount(count + 1)
console.log('# useEffect ==>','')
},[]);

หรือเราจะให้ useEffect ทำงานเมื่อ state ตัวใดตัวหนึ่งมีการ update value ก็ทำได้ เมื่อ มีการ setCat useEffect ก็จะทำงานทันที เพราะ useEffect(fn,[cat]) subscribe state cat ไว้

ยังสามารถ ให้ useEffect return function ออกมาได้ด้วย เป็น statement สุดท้ายที่จะทำงาน

ทำให้เราสะดวกต่อการใช้งาน Lifecycle มากขึ้น code เป็นระเบียบมากขึ้น และ กระชับขึ้นมากเลยครับ

ref : https://reactjs.org/docs/hooks-effect.html

--

--