Created
December 22, 2021 09:48
-
-
Save js2me/ab34ad47c2259ceaefa6c1c3174ea84d to your computer and use it in GitHub Desktop.
useConstant hook
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 { useRef } from 'react' | |
/** | |
* Создает константное значение в функциональном React компоненте | |
* useMemo не дает гарантий, что функция определения значения не вызовется повторно | |
* https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily | |
* https://reactjs.org/docs/hooks-reference.html#usememo | |
* | |
* @param defineValue функция определения значения | |
*/ | |
export const useConstant = <T>(defineValue: () => T): T => { | |
const ref = useRef<{ value: T }>() | |
if (!ref.current) { | |
ref.current = { value: defineValue() } | |
} | |
return ref.current.value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment