useState

#HelloFrontend #HelloErmine #HelloWorld2021

useState ใช้ทำอะไร ?

ใช้ประกาศตัวแปร state ให้กับ function component โดยใน 1 component จะประกาศกี่ครั้งก็ได้

ค่าของตัวแปร state จะถูกเก็บไว้กับ React

ค่าที่ useState รับได้

  • [ไม่ใส่ก็ได้] ค่าเริ่มต้นของตัวแปร state (ถ้าไม่กำหนดจะมีค่าเริ่มต้นเป็น undefined)

ค่าที่ useState จะ return

  • array ที่มีสมาชิก 2 ตัว คือ

    • ค่าปัจจุบันของตัวแปร state

    • function ที่ใช้เปลี่ยนแปลงตัวแปร state

useState ทำงานยังไง ?

  • เมื่อ component render ครั้งแรก : useState จะประกาศตัวแปร state และ return เป็น array ที่มีสมาชิกเป็นค่าเริ่มต้นที่เราส่งไป พร้อมกับ function ที่ใช้เปลี่ยนแปลงตัวแปร state

  • render ครั้งต่อ ๆ ไป : useState จะ return เป็น array ที่มีสมาชิกเป็นค่าปัจจุบันของตัวแปร state (ที่ React เก็บไว้ให้) พร้อมกับ function ที่ใช้เปลี่ยนแปลงตัวแปร state

ตัวอย่างการใช้งาน

import React, { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0);
 
  return  (
    <div>
      You have {count} cookies
      <br />
      <button onClick={() => setCount(count + 1)}>
        Steal a cookie
      </button>
    </div>
  )
}
...
    const [count, setCount] = useState(0);
...

จากตัวอย่าง เราประกาศตัวแปร state ชื่อ count มีค่าเริ่มต้นเป็น 0 และใช้ array destructuring เพื่อหยิบค่าออกมาจาก array ที่ useState return มาให้เรา

...
  return  (
    <div>
      You have {count} cookies
      <br />
      <button onClick={() => setCount(count + 1)}>
        Steal a cookie
      </button>
    </div>
  )

จากนั้นเรานำ count มาแสดงผล และมี button ที่เมื่อคลิกแล้ว จะเพิ่มค่า count ด้วย 1 ผ่านการเรียกใช้ setCount

การเปลี่ยนแปลงค่าตัวแปร state จะทำให้ component เกิดการ re-render เพื่อนำ state ล่าสุดไปใช้

แหล่งอ้างอิง

Last updated

Was this helpful?