usePrevious

Tags:

A React Hook that retains the different value of the state from the last render.

Scenes

  • Track the previous state: Used to record the changes in the state, so that related operations can be performed in the next render.
  • ...

Demo

Source
CurCount:
0
PreCount:
undefined
PrePreCount:
undefined
PrePrePreCount:
undefined
Count:
0
undefinedundefinedundefinedundefinedundefinedundefined

Usage

const prevState = usePrevious(state)

// When the state changes from 1 to 2, the value of prevState will be 1

Source

Click links below to view source on GitHub.

API

const previous = usePrevious(state, options)

State

The state of which you wish to retain the previous value, can be any valid JavaScript type.

Options

interface UsePreviousOptions {
  /**
   * An `isEqual` function used to compare whether the previous value is equal to the current value, defaults to `Object.is`.
   *
   * @param previous The previous value.
   * @param current The current value.
   * @returns Returns `true` if equal, otherwise returns `false`.
   *
   * @defaultValue `Object.is`
   */
  isEqual?(previous: any, current: any): boolean
  /**
   * Whether to compare deeply, defaults to `false`.
   *
   * @defaultValue false
   */
  deep?: boolean
}

if deep is true, isEqual will be ignored and the built-in deep comparison strategy will be used instead.

Returns

The different value of the state from the last render.