What is a custom hook in React JS?

majidbabaeifar

Majid Babaeifar

Posted on July 30, 2022

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.

💖 💪 🙅 🚩
majidbabaeifar
Majid Babaeifar

Posted on July 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related