Created
December 23, 2020 00:12
-
-
Save nandorojo/7e9e86d8edecdf4b782c8b036c8da08d to your computer and use it in GitHub Desktop.
React Hook that calls a function when a variable changes
This file contains 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
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] | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have a usage example
@nandorojo