AceDevHub
Intermediate React Interview QuestionsIntermediateConcept

React · Question 41

What is a custom Hook in React, and when should you create one?

Direct answer

A custom Hook is a function whose name starts with use and that can call other Hooks to package reusable stateful or synchronization logic.

useOnlineStatus.js
function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    const online = () => setIsOnline(true);
    const offline = () => setIsOnline(false);

    window.addEventListener("online", online);
    window.addEventListener("offline", offline);

    return () => {
      window.removeEventListener("online", online);
      window.removeEventListener("offline", offline);
    };
  }, []);

  return isOnline;
}

Custom Hooks let components reuse logic without introducing another visual component into the tree.