Custom hooks from the talk: https://youtu.be/J-g9ZJha8FE
Created
March 30, 2020 13:03
-
-
Save xsaamiir/fb6ea43ce113102bef52ab76f0d7fc8a to your computer and use it in GitHub Desktop.
Custom hooks in React
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 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]) | |
} |
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 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