useExperiment.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import noop from 'lodash/noop';
  2. import {unassignedValue} from 'sentry/data/experimentConfig';
  3. import HookStore from 'sentry/stores/hookStore';
  4. import {ExperimentAssignment, ExperimentKey} from 'sentry/types/experiments';
  5. type UseExperimentOptions = {
  6. /**
  7. * By default this hook will log the exposure of the experiment upon mounting
  8. * of the component.
  9. *
  10. * If this is undesirable, for example if the experiment is hidden behind
  11. * some user action beyond this component being mounted, then you will want
  12. * to customize when exposure to the experiment has been logged.
  13. *
  14. * NOTE: If set to false, YOU ARE RESPONSIBLE for logging exposure of the
  15. * experiment!! If you do not log exposure your experiment will not be
  16. * correct!!
  17. */
  18. logExperimentOnMount?: boolean;
  19. };
  20. type UseExperimentReturnValue<E extends ExperimentKey> = {
  21. experimentAssignment: ExperimentAssignment[E] | typeof unassignedValue;
  22. /**
  23. * Call this method when the user has been exposed to the experiment.
  24. * You do not need to call this unless you have disabled logging on mount.
  25. */
  26. logExperiment: () => void;
  27. };
  28. export type UseExperiment = <E extends ExperimentKey>(
  29. experiment: E,
  30. options?: UseExperimentOptions
  31. ) => UseExperimentReturnValue<E>;
  32. const DEFAULT_RETURN_VALUE = {
  33. experimentAssignment: unassignedValue,
  34. logExperiment: noop,
  35. };
  36. export const useExperiment: UseExperiment = (...params) => {
  37. return (
  38. HookStore.get('react-hook:use-experiment')[0]?.(...params) ?? DEFAULT_RETURN_VALUE
  39. );
  40. };