Skip to content

Instantly share code, notes, and snippets.

@clintonmedbery
Last active February 4, 2020 05:37
Show Gist options
  • Save clintonmedbery/70024ded901a0eb64e28d545970900c0 to your computer and use it in GitHub Desktop.
Save clintonmedbery/70024ded901a0eb64e28d545970900c0 to your computer and use it in GitHub Desktop.
Useful Hooks
//Hook used to determine if it is a component's first mount
//Useful to put in useEffect functions that share data calls but not all the same calls
import { useRef, useEffect } from 'react'
//https://stackoverflow.com/a/56267719/3058839
export const useIsMount = () => {
const isMountRef = useRef(true)
useEffect(() => {
isMountRef.current = false
}, [])
return isMountRef.current
}
//Ex:
// useEffect(() => {
// getData(param1, param2)
// getOtherData(param1)
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [param1])
// useEffect(() => {
// //Since two useEffects are making this call, we want to make sure this is not the initial mount
// if (!isMount) {
// getData(param1, param2)
// }
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [param2])
//Hook meant to returned a debounced variable for a search etc.
import { useState, useEffect } from 'react'
//https://dev.to/gabe_ragland/debouncing-with-react-hooks-jci
export default function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
//Shuts linter up about delay
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value])
return debouncedValue
}
//Ex:
// let debouncedSearchTerm = useDebounce(searchTerm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment