Skip to content

Instantly share code, notes, and snippets.

@nandorojo
Created December 23, 2020 00:12
Show Gist options
  • Save nandorojo/7e9e86d8edecdf4b782c8b036c8da08d to your computer and use it in GitHub Desktop.
Save nandorojo/7e9e86d8edecdf4b782c8b036c8da08d to your computer and use it in GitHub Desktop.
React Hook that calls a function when a variable changes
import { useEffect, useRef } from 'react'
export default function useOnChange<T>(
value: T,
effect: (prev: T, next: T) => void
) {
const latestValue = useRef(value)
const callback = useRef(effect)
callback.current = effect
useEffect(
function onChange() {
if (value !== latestValue.current) {
callback.current(latestValue.current, value)
}
},
[value]
)
}
@WhyFenceCode
Copy link

Do you have a usage example
@nandorojo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment