use_const.ts 366 B

123456789101112
  1. import * as React from "react";
  2. // Why doesn't React have this functionality built-in? (and implemented more efficiently than hacking with useRef)
  3. export function useConst<T>(initialCb: ()=>T): T {
  4. const ref = React.useRef<T>();
  5. if (ref.current === undefined) {
  6. const initialValue = initialCb();
  7. ref.current = initialValue;
  8. }
  9. return ref.current!;
  10. }