DEV Community

Majid Babaeifar
Majid Babaeifar

Posted on

What is a custom hook in React JS?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
When we want to share logic between two JavaScript functions, we extract it to a third function.
Both components and Hooks are functions, so this works for them too! A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. Unlike a React component, a custom Hook doesn’t need to have a specific signature. We can decide what it takes as arguments, and what, if anything, it should return. In other words, it’s just like a normal function. Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it. for example :

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we can use other hooks in our custom hook.

Top comments (2)

Collapse
 
brense profile image
Rense Bakker

Custom hooks are great... However I do have some issues with the code inside your custom hook 😅 Defining functions in a useEffect and having a useEffect without a dependency array (executed on every render) is not very good for performance. The cleanup function is good and very important, but you should probably also add a dependency array, so your ChatAPI subscription will only happen when the component is mounted or when one of the dependencies changed. The function definition you can also move outside of the useEffect and memoize it.

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  const handleStatusChange = useCallback((status) => {
    setIsOnline(status.isOnline);
  }, []);

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  }, [handleStatusChange, friendID]);

  return isOnline;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
majidbabaeifar profile image
Majid Babaeifar

Thank you for your opinion. However, the purpose of this article was about custom hooks and I was trying to show that you can use a custom hook inside another hook. But you made some great points. Thank you for your time.