usePrevious Hook

Simple react hook for getting the previous value


Usage:

const [state, setState] = useState("foobar")

const previousVal = usePrevious(state)

setState("foobaz")

console.log(previousVal) // --> "foobar"


Hook (TS):

import { useRef, useEffect } from 'react'
export function usePrevious<T>(value: T) {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

Hook (JS):

import { useRef, useEffect } from 'react'
export function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}