Last active
April 8, 2020 09:49
-
-
Save krutoo/0d55d7bc8aee91028e0a012f582a181f to your computer and use it in GitHub Desktop.
Custom react hooks
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 isEqual from 'lodash/isEqual'; | |
import { useState, useEffect, useRef, useMemo as defaultUseMemo } from 'react'; | |
export const useOnMount = callback => { | |
useEffect(callback, []); | |
}; | |
export const useForceUpdate = () => { | |
const [, setState] = useState(null); | |
return () => setState(Math.random()); | |
}; | |
export const useOnUpdate = callback => { | |
const isInitialUpdate = useRef(true); | |
useEffect(() => { | |
if (isInitialUpdate.current) { | |
isInitialUpdate.current = false; | |
} else { | |
callback(); | |
} | |
}); | |
}; | |
export const useOnUnmount = callback => { | |
useEffect(() => () => callback(), []); | |
}; | |
export const useConstant = (calculateValue, dependencies) => { | |
const { current: memoFn } = useRef(calculateValue); | |
const { current: memoDeps } = useRef(dependencies); | |
const { current: memoValue } = useRef(memoFn(memoDeps)); | |
return memoValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment