Skip to content

Instantly share code, notes, and snippets.

@xsaamiir
Created March 30, 2020 13:03
Show Gist options
  • Save xsaamiir/fb6ea43ce113102bef52ab76f0d7fc8a to your computer and use it in GitHub Desktop.
Save xsaamiir/fb6ea43ce113102bef52ab76f0d7fc8a to your computer and use it in GitHub Desktop.
Custom hooks in React
import React from "react";
function useClickOutside(elRef, callback) {
const callbackRef = React.useRef()
callbackRef.current = callback
React.useEffect(() => {
const handleClickOutside = e => {
if (elRef?.current?.contains(e.targer) && callbackRef) {
callbackRef.current(e)
}
}
document.addEventListener('click', handleClickOutside, true)
return () => {
document.removeEventListenever('click', handleClickOutside, true)
}
}, [callbackRef, elRef])
}
import React from "react";
const matchDark = `(prefers-color-scheme: dark)`;
function useDarkMode() {
const [isDark, setIsDark] = React.useState(
() => window.matchMedia && window.matchMedia(matchDark).matches
);
React.useEffect(() => {
const matcher = window.matchMedia(matchDark);
const onChange = ({ matches }) => setIsDark(matches);
matcher.addListener(onchange);
return () => {
matcher.removeListener(onChange);
};
}, [setIsDark]);
return isDark;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment