usePrevious

NEW

React hook to track the previous value of a variable.

Add the hook via the CLI:

npx @novajslabs/cli add usePrevious

Or copy and paste the code into your project:

import { useRef } from 'react'

export default function usePrevious<T>(value: T): T | undefined {
  const currentRef = useRef<T>(value)
  const previousRef = useRef<T>()

  if (currentRef.current !== value) {
    previousRef.current = currentRef.current
    currentRef.current = value
  }

  return previousRef.current
}

React 16.8 or higher

  • Name
    value
    Type
    T
    Required
    required
    Description

    The value to track .

  • Name
    previousValue
    Type
    T
    Description

    The previous value of value.

import { usePrevious } from './hooks/usePrevious'
import { useState } from 'react'

const App = () => {
  const [value, setValue] = useState(0)
  const previousValue = usePrevious(value)

  return (
    <button onClick={() => setValue(value + 1)}>
      Current: {value} - Previous: {previousValue}
    </button>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Track the previous state in a form to validate changes
  • Implement undo functionality in an editor
  • Compare the current and previous prop values in a component
  • Monitor previous API request results for comparison
  • Track previous user inputs in a search bar to optimize suggestions