Skip to content

Instantly share code, notes, and snippets.

@jamesplease jamesplease/0.usage.js
Last active Apr 3, 2019

Embed
What would you like to do?
My favorite custom hook, useOnChange
const [someState, setSomeState] = useState(true);
// It's just like componentDidUpdate!
useOnChange((current, prev) => {
console.log('It just changed!', current, prev);
}, someState);
// ...see the below files for the source.
import { useEffect } from 'react';
import usePrevious from './use-previous';
export default function useOnChange(callback, val) {
const previous = usePrevious(val);
useEffect(() => {
if (typeof previous !== 'undefined' && val !== previous) {
callback(val, previous);
}
}, [val, previous]);
}
import { useEffect, useRef } from 'react';
export default function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.