Skip to content

Instantly share code, notes, and snippets.

@js2me
Created December 22, 2021 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save js2me/ab34ad47c2259ceaefa6c1c3174ea84d to your computer and use it in GitHub Desktop.
Save js2me/ab34ad47c2259ceaefa6c1c3174ea84d to your computer and use it in GitHub Desktop.
useConstant hook
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