"use client"; import { type Dispatch, type SetStateAction, useCallback, useRef, useState } from "react"; /** * `useState` + getter ที่อัปเดตทันที (synchronous) — สำหรับ optimistic UI * * callback ที่คำนวณ "รายการถัดไป" จากรายการปัจจุบันห้ามอ่านค่าตอน render: * mutation สองครั้งใน tick เดียว (drag-and-drop, automation, bulk action) จะเริ่มจาก * รายการเก่าทั้งคู่ และครั้งที่สองทับครั้งแรกเงียบ ๆ — `getLatest()` คืนค่าจาก `set` ครั้งล่าสุดเสมอ * แม้ React ยังไม่ commit * * const [tasks, setTasks, getLatestTasks] = useTrackedState([]); * function move(id: string, to: string) { * const current = getLatestTasks(); // ไม่ใช่ `tasks` * setTasks(current.map((t) => (t.id === id ? { ...t, section: to } : t))); * } */ export function useTrackedState( initial: T | (() => T), ): readonly [T, Dispatch>, () => T] { const [state, setState] = useState(initial); const latestRef = useRef(state); const set = useCallback>>((update) => { const next = typeof update === "function" ? (update as (previous: T) => T)(latestRef.current) : update; latestRef.current = next; setState(next); }, []); const getLatest = useCallback(() => latestRef.current, []); return [state, set, getLatest] as const; }