refToCallback.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Unmemoized version of {@link useRefToCallback}
  3. * @see {@link useRefToCallback}
  4. * @param ref
  5. */
  6. export function refToCallback(ref) {
  7. return (newValue) => {
  8. if (typeof ref === 'function') {
  9. ref(newValue);
  10. }
  11. else if (ref) {
  12. ref.current = newValue;
  13. }
  14. };
  15. }
  16. const nullCallback = () => null;
  17. // lets maintain a weak ref to, well, ref :)
  18. // not using `kashe` to keep this package small
  19. const weakMem = new WeakMap();
  20. const weakMemoize = (ref) => {
  21. const usedRef = ref || nullCallback;
  22. const storedRef = weakMem.get(usedRef);
  23. if (storedRef) {
  24. return storedRef;
  25. }
  26. const cb = refToCallback(usedRef);
  27. weakMem.set(usedRef, cb);
  28. return cb;
  29. };
  30. /**
  31. * Transforms a given `ref` into `callback`.
  32. *
  33. * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)}
  34. *
  35. * @param {ReactRef} ref
  36. * @returns {Function}
  37. *
  38. * @see https://github.com/theKashey/use-callback-ref#reftocallback
  39. *
  40. * @example
  41. * const ref = useRef(0);
  42. * const setRef = useRefToCallback(ref);
  43. * 👉 setRef(10);
  44. * ✅ ref.current === 10
  45. */
  46. export function useRefToCallback(ref) {
  47. return weakMemoize(ref);
  48. }