ย้ายจาก React Class Component มาเป็น Functional Component ง่ายกว่าที่คิด
ใครที่ใช้ React แล้วเขียนด้วย Class Componentลองย้ายมาเขียน Functional Component (Hook) ดูน้า ไม่ยากเลย ทำให้โค๊ดอ่านง่ายมากขึ้นด้วย และเขียนง่ายขึ้น
วันนี้เอาตัวอย่างที่ใช้บ่อยๆ ใน React TypeScript เทียบกันให้เห็น จะๆ เลย
Local State
เราสามารถแปลงจาก Class Component ด้านล่างนี้
;
;
;
ให้เป็น Functional Component แบบนี้ได้
;
;
;
ทำไมถึงไม่แนะนำ React.FC
หรือ React.FunctionComponent
/React.VoidFunctionComponent
อ่านรายละเอียดใน Functional Component
Handle Click Event
เราสามารถแปลงจาก Class Component ด้านล่างนี้
;
;
Note: Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison. Read more at React Official Doc.
ให้เป็น Functional Component แบบนี้ได้
;
;
;
componentDidMount() in React Hook
หนึ่งใน React Lifecyle ที่ใช้บ่อยๆ มากๆ คือ componentDidMount() ซึ่งจะทำครั้งแรก ครั้งเดียวเมื่อ Component โหลดเสร็จ
ข้อสังเกตุ useEffect
ต้องการรับ 2 parameters ถ้าอยากให้เหมือน componentDidMount()
ให้ใส่ Array เปล่าๆ ใน parameters ตัวที่สอง []
componentWillUnmount() in React Hook
อีกหนึ่งใน React Lifecyle ที่มีใช้บ้างคือคือ componentWillUnmount() ซึ่งจะทำงานครั้งสุดท้ายครั้งเดียวก่อนที่ Component ถูกเอาออก (Component is unmounted and destroyed)
เราสามารถใช้ประโยชน์จาก function useEffect
ได้ ตรงที่ return ของ parameters ตัวแรกของ useEffect
โดยเราสามารถ remove event listeners หรือล้างข้อมูลอะไรบางอย่าง ก็ได้ครับ
Cross published at .NET Thailand
Acknowledgement: Thank you .net thailand team to review this article: dotnetthailand.github.io#83