javascriptreactjsreact-hookses6-modulesjavascript-import

export react hook by changing its signature


I want to change a hook name and its return values while exporting them. Here is my use case. I want to use notistack api to show some toasts in my application. However, because I don't like the name snackbar I want to change it to toast. Here is how I start doing it:

export { SnackbarProvider as ToastProvider, useSnackbar as useToast } from 'notistack';

But I can't manage to change the name of the variables returned from the useSnackbar hook.

const { enqueueSnackbar, closeSnackbar } = useSnackbar();

should be

const { addToast, closeToast } = useToast();

how can I achieve this?

thank you.


Solution

  • You can define a custom hook that wraps the useSnackbar hook as follow:

    import { SnackbarProvider, useSnackbar } from 'notistack';
    
    export const useToast = () => {
      const { enqueueSnackbar, closeSnackbar } = useSnackbar();
      return { addToast: enqueueSnackbar, closeToast: closeSnackbar };
    };
    
    export const SnackbarProvider = ToastProvider;
    

    You can learn more about building custom hooks on the documentation: https://reactjs.org/docs/hooks-custom.html