Search code examples
reactjstypescriptmantine

How to manage notification with one state


This is a React project with Mantine's Notification System demo. It has a lot of function components using notification.

const A = () => {
  useEffect(() => {
    notifications.show({
        // config
    });
  }, []);

  return <></>;
};
const B = () => {
  useEffect(() => {
    notifications.show({
        // config
    });
  }, []);

  return <></>;
};
const C = () => {
  useEffect(() => {
    notifications.show({
        // config
    });
  }, []);

  return <></>;
};

Now, we have a global state named muteMode, if user enable the state, all notification disabled. So I have to change code as below

const A = () => {
  const { muteMode } = useGlobalState(state => state);
  
  useEffect(() => {
    if (muteMode) {
      notifications.show({
        // config
      });
    }
  }, [muteMode]);

  return <></>;
};
// The B、C function components are same as A

I think is not good code. Because I have modify all business about notifications. If I add more business about notification, I have to modify again. Does something like Notification Manager exist?


Solution

  • You can create a custom hook so that you don't have to rewrite everywhere. Example -

    const useNotification = (config) => {
      const { muteMode } = useGlobalState(state => state);
      
      useEffect(() => {
        if (muteMode) {
          notifications.show(config);
        }
      }, [muteMode, config]);
    
      return null;
    };
    

    In your component use it like this -

    const A = () => {
      useNotification({ title: 'Notification A' })
    
      return <></>;
    };
    
    const B = () => {
      useNotification({ title: 'Notification B' })
    
      return <></>;
    };
    
    const C = () => {
      useNotification({ title: 'Notification C' })
    
      return <></>;
    };
    

    Hope this helps!