Skip to content

usePrevious

Stores the previous value from the last render.

Stores the previous value from the last render.

Import

import { usePrevious } from '@kamod-ch/hooks'

Live demo

Basic demo

Stores the previous value from the last render.

Current: first

Previous: none

import { useState } from 'preact/hooks'
import { usePrevious } from '@kamod-ch/hooks'

export default function UsePreviousDemo() {
  const [value, setValue] = useState('first')
  const previous = usePrevious(value)

  return (
    <div>
      <input value={value} onInput={(event) => setValue(event.currentTarget.value)} />
      <p><strong>Current:</strong> {value}</p>
      <p><strong>Previous:</strong> {previous ?? 'none'}</p>
    </div>
  )
}

API

TypeScript signature
export type ShouldUpdateFunc<T> = (prev?: T, next?: T) => boolean;
declare function usePrevious<T>(state: T, shouldUpdate?: ShouldUpdateFunc<T>): T | undefined;
export default usePrevious;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.