use-constant.mjs 531 B

123456789101112131415161718
  1. import { useRef } from 'react';
  2. /**
  3. * Creates a constant value over the lifecycle of a component.
  4. *
  5. * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer
  6. * a guarantee that it won't re-run for performance reasons later on. By using `useConstant`
  7. * you can ensure that initialisers don't execute twice or more.
  8. */
  9. function useConstant(init) {
  10. const ref = useRef(null);
  11. if (ref.current === null) {
  12. ref.current = init();
  13. }
  14. return ref.current;
  15. }
  16. export { useConstant };