Skip to content

[toast] Make useToastManager and createToastManager generic functions - #3882

Merged
atomiks merged 7 commits into
mui:masterfrom
unifygtm:generic-use-toast-manager
Feb 2, 2026
Merged

atomiks merged 7 commits into
mui:masterfrom
unifygtm:generic-use-toast-manager

Conversation

@solastley

@solastley solastley commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR makes the hook useToastManager a generic function so that the returned toasts, add, update, and promise functions all inherit the type argument provided to useToastManager.

I thought this might be worth a discussion. For my use case (and I imagine this is true for most folks, but perhaps not), I have a single type which represents a discriminated union of all possible types that can be used as the type of data in toast objects. When I access the toast manager with useToastManager, it would be very convenient to specify this type at that time and not need to type cast when using the toasts on the returned toast manager.

Example

For example, today I need to do something like the following:

enum ToastType {
  A = 'A',
  B = 'B',
}

type CustomToastA = {
  type: ToastType.A;
  someCustomField: boolean;
  ...
};

type CustomToastB = {
  type: ToastType.B;
  someOtherField: string;
  ...
};

type CustomToast = CustomToastA | CustomToastB | ...

const MyComponent = () => {
  const { toasts } = Toast.useToastManager();
  
  return (
    <Toast.Viewport>
      {toasts.map((toast) => {
        // Need to type cast here
        const typedToastData = toast.data as CustomToast;
        ...
      })}
    </Toast.Viewport>
  );
};

With this change, if the type CustomToast were provided to useToastManager as a type argument in the above example, then toast.data would be automatically typed as CustomToast.

Concerns

This change modifies add, update, and promise to no longer be generic. So I believe this would constitute a breaking change for those methods if consumers are currently providing type arguments to them.

@pkg-pr-new

pkg-pr-new Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@3882
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@3882
    

commit: 0a4994a

@mui-bot

mui-bot commented Jan 28, 2026 •

Copy link
Copy Markdown

Bundle size report

Bundle Parsed size Gzip size
@base-ui/react 0B(0.00%) 0B(0.00%)

Details of bundle changes


Check out the code infra dashboard for more information about this PR.

@greptile-apps

greptile-apps Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Overview

Greptile Summary

This PR makes useToastManager and createToastManager generic functions, allowing consumers to specify toast data types at the function level rather than on individual method calls.

Key Changes:

  • Both functions now accept a generic Data extends object = any parameter
  • The add, update, and promise methods now use a nested generic T extends Data = Data pattern, defaulting to the manager's Data type
  • toasts array is now typed as ToastContext<Data>['toasts'] instead of ToastContext<any>['toasts']
  • Comprehensive type specs added to verify both new and legacy usage patterns

Backward Compatibility:
The implementation maintains backward compatibility through:

  • Default generic parameter any on the manager functions
  • Nested generics on methods that still allow per-call type specification
  • Legacy usage pattern still works: manager.add<CustomType>(...)

Documentation:
Generated API documentation automatically updated to reflect the type signature changes.

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The implementation is clean, well-tested, and maintains full backward compatibility. The type specs thoroughly verify both new and legacy usage patterns. The generic constraint pattern T extends Data = Data is idiomatic TypeScript that preserves type safety while allowing flexibility.
  • No files require special attention

Important Files Changed

Filename Overview
packages/react/src/toast/createToastManager.ts Makes createToastManager generic with Data extends object = any, allowing type-safe toast data while maintaining backward compatibility through default generic parameter and internal generic methods
packages/react/src/toast/useToastManager.ts Makes useToastManager generic with Data extends object = any, propagating type to returned toasts array and methods, enabling type-safe toast management
packages/react/src/toast/createToastManager.spec.tsx Adds comprehensive type specs verifying both new generic manager behavior and legacy per-method generic usage, ensuring backward compatibility
packages/react/src/toast/useToastManager.spec.tsx Adds comprehensive type specs verifying both new generic hook behavior and legacy per-method generic usage, with additional test for typed toasts array

@netlify

netlify Bot commented Jan 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 0a4994a
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/698001cb63e6dc0008aed21b
😎 Deploy Preview https://deploy-preview-3882--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@mj12albert mj12albert changed the title [base-ui][Toast] make useToastManager generic function [toast] Make useToastManager generic function Jan 29, 2026
@mj12albert mj12albert added the component: toast Changes related to the toast component. label Jan 29, 2026
@atomiks

atomiks commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor

You should be able to make it backward‑compatible while still enabling the new typed manager by defaulting the method generic to the hook's Data type

export function useToastManager<Data extends object = any>(): UseToastManagerReturnValue<Data> {

...

export interface UseToastManagerReturnValue<Data extends object = any> {
  toasts: ToastContext<Data>['toasts'];
  add: <T extends object = Data>(options: ToastManagerAddOptions<T>) => string;
  close: (toastId: string) => void;
  update: <T extends object = Data>(toastId: string, options: ToastManagerUpdateOptions<T>) => void;
  promise: <Value, T extends object = Data>(
    promise: Promise<Value>,
    options: ToastManagerPromiseOptions<Value, T>,
  ) => Promise<Value>;
}

Spec file

/* eslint-disable react-hooks/rules-of-hooks */
import { expectType } from '#test-utils';
import { useToastManager } from './useToastManager';

type ToastPayload = {
  id: string;
  count: number;
};

const typedManager = useToastManager<ToastPayload>();

const typedToastData = typedManager.toasts[0]?.data;
expectType<ToastPayload | undefined, typeof typedToastData>(typedToastData);

const typedAddId = typedManager.add({
  title: 'typed',
  data: {
    id: 'typed',
    count: 1,
  },
});
expectType<string, typeof typedAddId>(typedAddId);

typedManager.update('typed', {
  data: {
    id: 'typed-update',
    count: 2,
  },
});

typedManager.promise(Promise.resolve(2), {
  loading: 'loading',
  success: (value) => ({
    title: `${value}`,
    data: {
      id: 'typed-success',
      count: value,
    },
  }),
  error: 'error',
});

const legacyManager = useToastManager();

const legacyAddId = legacyManager.add<ToastPayload>({
  title: 'legacy',
  data: {
    id: 'legacy',
    count: 3,
  },
});
expectType<string, typeof legacyAddId>(legacyAddId);

legacyManager.update<ToastPayload>('legacy', {
  data: {
    id: 'legacy-update',
    count: 4,
  },
});

legacyManager.promise<number, ToastPayload>(Promise.resolve(5), {
  loading: 'loading',
  success: (value) => ({
    title: `${value}`,
    data: {
      id: 'legacy-success',
      count: value,
    },
  }),
  error: 'error',
});

@solastley

Copy link
Copy Markdown
Contributor Author

@atomiks nice, just updated the PR with your suggested changes. Did you want me to add that spec as well, or were you just sharing to demonstrate that it works as expected?

If you'd like me to add the spec, let me know.

@atomiks

atomiks commented Jan 30, 2026

Copy link
Copy Markdown
Contributor

@solastley yeah, should add it

@solastley

Copy link
Copy Markdown
Contributor Author

@atomiks hm, might be missing something, but I don't think these tests work since useToastManager can only run within a React component which is rendered within a Toast.Provider.

@atomiks

atomiks commented Jan 30, 2026

Copy link
Copy Markdown
Contributor

The spec file is only for types, it doesn't test runtime behavior. We have other spec files (filename.spec.tsx) for this purpose. /* eslint-disable react-hooks/rules-of-hooks */ is used to disable the linting.

@solastley

Copy link
Copy Markdown
Contributor Author

@atomiks done

@atomiks

atomiks commented Jan 31, 2026

Copy link
Copy Markdown
Contributor

@solastley thanks! I think this also applies to createToastManager?

@solastley

Copy link
Copy Markdown
Contributor Author

@atomiks yeah good call. Modified createToastManager to be generic as well and added the relevant spec.

add: <Data extends object>(options: ToastManagerAddOptions<Data>) => string;
export interface UseToastManagerReturnValue<Data extends object = any> {
toasts: ToastContext<Data>['toasts'];
add: <T extends object = Data>(options: ToastManagerAddOptions<T>) => string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These need to be T extends Data = Data to catch wrong shaped payloads:

typedManager.add({
  title: 'wrong-shape',
  data: {
    id: 'test',
    // @ts-expect-error - message is not a valid property
    message: 'not a number',
  },
});

typedManager.add({
  title: 'wrong-shape',
  // @ts-expect-error - count is a missing property
  data: {
    id: 'test',
  },
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@atomiks fixed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add those calls I made to the spec file?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@atomiks done 🫡

@atomiks

atomiks commented Feb 2, 2026

Copy link
Copy Markdown
Contributor

@greptileai

@atomiks atomiks left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution @solastley!

@atomiks atomiks changed the title [toast] Make useToastManager generic function [toast] Make useToastManager and createToastManager generic functions Feb 2, 2026
@atomiks
atomiks merged commit 5d9253c into mui:master Feb 2, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: toast Changes related to the toast component. typescript

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants