Skip to content

Instantly share code, notes, and snippets.

@bpander
Created February 24, 2022 16:55
Show Gist options
  • Save bpander/b0524a5d4a33052f42e4ac6b2e78e584 to your computer and use it in GitHub Desktop.
Save bpander/b0524a5d4a33052f42e4ac6b2e78e584 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from 'react';
export const usePreviousDifferent = <T>(value?: T): T | undefined => {
const shortTermRef = useRef<T | undefined>(value);
const longTermRef = useRef<T>();
useEffect(() => {
shortTermRef.current = value;
return () => { longTermRef.current = value; };
}, [value]);
return (shortTermRef.current === value) ? longTermRef.current : shortTermRef.current;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment