usePrevious lưu giá trị trước đó của một value sử dụng useRef.
Sau mỗi render, ref được cập nhật với value hiện tại nhưng function trả về ref.current (value từ render trước).
tsx
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined)
// useEffect không có deps chạy sau MỖI render
// → ghi ref SAU khi render hiện tại đã xong
// → lần render tiếp theo, ref.current là giá trị CŨ
useEffect(() => {
ref.current = value
})
return ref.current
}
// Ví dụ sử dụng
const Counter = () => {
const [count, setCount] = useState(0)
const prevCount = usePrevious(count)
return (
<p>
Current: {count}, Previous: {prevCount ?? 'none'}
</p>
)
}usePrevious stores the previous value of a variable using useRef.
After each render the ref is updated with the current value, but the function returns ref.current — the value from the previous render.
tsx
function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined)
// useEffect with no deps runs after EVERY render
// → writes to ref AFTER the current render completes
// → on the next render, ref.current holds the OLD value
useEffect(() => {
ref.current = value
})
return ref.current
}
// Usage example
const Counter = () => {
const [count, setCount] = useState(0)
const prevCount = usePrevious(count)
return (
<p>
Current: {count}, Previous: {prevCount ?? 'none'}
</p>
)
}