Coding for Notify Hook

Explore the implementation and complete the code for creating your first custom Notify hook.

Getting started

In the previous lesson, two functions were identified as needed as part of the Notify hook.

  • A function to show the notification message, called notifyUser.
  • A function to hide the notification message, called clearNotification.

Since we are automatically hiding the message after three seconds, clearNotification can be handled internally and does not need to be exposed outside the hook. Simply, return the notifyUser function as the output of the Notify hook.

Later, a component can use Notify hook like this:

const MyComponent = () => {
  const { notifyUser } = useNotifyHook();
  // some code here
}

Skeleton implementation

As mentioned previously, the logic to clear the notification message can be handled within the Notify hook. Use setTimeout to achieve it after waiting 3 seconds.

The notifyUser function is going to accept two arguments:

  • The message to be displayed.
  • A boolean for isError to be used later for error styling.

Here is the basic structure for the Notify hook.

const NOTIFY_TIME = 3000; // ms

export const useNotifyHook = () => {
  const clearNotification = () => {
    setTimeout(() => {
      // TODO: Dispatch action to clear notification message
    }, NOTIFY_TIME);
  };

  const notifyUser = (message, isError = false) => {
    // TODO: Dispatch action to enable notification message
    clearNotification();
  };

  return { notifyUser };
};

The sample usage will look like the example above. The useNotifyHook hook call will return the notifyUser function. When a user clicks the button, notifyUser is used to show a notification message.

const MyComponent = () => {
  const { notifyUser } = useNotifyHook();
  
  const handleClick = () => {
    notifyUser('React Hooks are amazing!')
  };
  
  return (
    <button onClick={handleClick }>Click here</button>
  );
};

Get hands-on with 1400+ tech skills courses.