File size: 498 Bytes
2bd3674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {useRef} from 'react';

type UninitializedMarker = Readonly<Record<string, unknown>> | symbol;
const UNINITIALIZED: UninitializedMarker =
  typeof Symbol === 'function' && typeof Symbol() === 'symbol'
    ? Symbol()
    : Object.freeze({});

export default function useStable<T>(initialValueCallback: () => T): T {
  const ref = useRef<T | UninitializedMarker>(UNINITIALIZED);
  if (ref.current === UNINITIALIZED) {
    ref.current = initialValueCallback();
  }
  return ref.current as T;
}