บันทึกความเข้าใจการ Using Hooks in a React Redux

Nantipat
2 min readDec 18, 2020

บทความนี้แค่บันทึกความเข้าใจในการใช้ hook of react-redux และรวมบทความที่มีคนเขียนไว้แล้ว

ปัญหาคือเวลา update value หรือ function ตัวใดตัวนึงมันดัน update หมดเลยต้องใช้ useCallback and useMemo แก้ปัญหา

useCallback vs useMemo

Abstract

The React docs say that useCallback:

Returns a memoized callback.

And that useMemo:

Returns a memoized value.

useSelector มีความแตกต่างกับ mapState

  • The selector may return any value as a result, not just an object.
  • When an action is dispatched, จะทำการเปรียบเทียบอ้างอิงของผลลัพท์ก่อนหน้าและค่าปัจจุบัน หากต่างกันจะบังคับให้ re-render
  • The selector function does not receive an ownProps argument. ยังไงก็ตาม props ผ่าน closure ได้
  • ต้องใช้ความระมัดระวังเป็นพิเศษเมื่อใช้ตัวเลือกการช่วยจำ
  • useSelector() uses strict === reference equality checks by default, not shallow equality

คุณสามารถเรียก useSelector() หลายครั้ง แต่ละครั้งจะ subscription ไปนัง Redux

a dispatched action that causes multiple useSelector()s in the same component to return new values should only result in a single re-render.

การเปรียบเทียบและอัปเดตความเท่าเทียมกัน

เมื่อคอมโพเนนต์ของฟังก์ชันแสดงผลฟังก์ชันตัวเลือกที่จัดเตรียมไว้จะถูกเรียกใช้และผลลัพธ์จะถูกส่งกลับจาก useSelector ()

ยังไงก็ตามเมื่อ an action is dispatched to the Redux store

useSelector() only forces a re-render if the selector result appears to be different than the last result.

ด้วย useSelector () การส่งคืนอ็อบเจ็กต์ใหม่ทุกครั้งจะบังคับให้ re-render ตามค่าเริ่มต้นเสมอ หากคุณต้องการดึงข้อมูลหลายค่าจากร้านค้าคุณสามารถ:

ด้วย mapState แต่ละเขตข้อมูลทั้งหมดถูกส่งคืนในวัตถุที่รวมกัน

ไม่สำคัญว่าออบเจ็กต์ที่ส่งคืนจะเป็นข้อมูลอ้างอิงใหม่หรือไม่ — connect () เพียงแค่เปรียบเทียบแต่ละฟิลด์

  • Call useSelector() multiple times, with each call returning a single field value
  • ใช้ Reselect หรือไลบรารีที่คล้ายกันเพื่อสร้างตัวเลือกแบบบันทึกที่ส่งคืนค่าหลายค่าในอ็อบเจ็กต์เดียว แต่จะส่งคืนอ็อบเจ็กต์ใหม่เมื่อค่าใดค่าหนึ่งเปลี่ยนไปเท่านั้น
  • Use the shallowEqual function from React-Redux as the equalityFn argument to useSelector(), like:

--

--