Created
August 16, 2025 23:26
-
-
Save romgrk/3e4026ce4acda65211cd14b5a6ed4bff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client'; | |
import { useIsoLayoutEffect } from './useIsoLayoutEffect'; | |
import { useRefWithInit } from './useRefWithInit'; | |
export function usePreviousValue<T>(value: T) { | |
const instance = useRefWithInit(createPreviousValue, value).current; | |
instance.next = value; | |
instance.dependencies[0] = value; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
useIsoLayoutEffect(instance.effect, instance.dependencies); | |
return instance; | |
} | |
function createPreviousValue<T>(value: T) { | |
const instance = { | |
current: value, | |
next: value, | |
dependencies: [value], | |
effect: () => { | |
instance.current = instance.next; | |
instance.dependencies = [instance.next]; | |
}, | |
}; | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment