GuobaGuoba Utils

usePrevious

@guoba-ai/hook / usePrevious

Function: usePrevious()

function usePrevious<T>(value): T | undefined;

Defined in: usePrevious.ts:24

Track the previous value of a variable across renders.

Parameters

value

T

The current value to track

Returns

T | undefined

The value from the previous render, or undefined on the first render

Example

const [count, setCount] = useState(0)
const prevCount = usePrevious(count)
// After setCount(1): prevCount === 0
// After setCount(2): prevCount === 1

const prevName = usePrevious(name)
// First render: prevName === undefined

const prevUser = usePrevious(user)
// Object values are returned by their previous reference

Warning

Returns undefined on the first render because there is no previous value yet.

On this page