Skip to content

Instantly share code, notes, and snippets.

@marten-cz
Last active March 30, 2022 10:56
Show Gist options
  • Save marten-cz/0e212e29b8ef6e0c1ba75a07c9bd7026 to your computer and use it in GitHub Desktop.
Save marten-cz/0e212e29b8ef6e0c1ba75a07c9bd7026 to your computer and use it in GitHub Desktop.
React hooks
import { useEffect, useRef } from 'react';
import isEqual from 'lodash/isEqual';
export const useCompare = (value) => {
const prevValue = usePrevious(value);
return !isEqual(prevValue, value);
};
export const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
import { useEffect } from 'react';
const useOutsideClick = (ref, onOutsideClick) => {
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
onOutsideClick();
}
}
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
});
};
export default useOutsideClick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment