Files
developer-roadmap/src/data/question-groups/react/content/custom-hook.md
T
Arik ChakmaandKamran Ahmed edcf0e683d Add react questions (#4492)
* Add more questions

* wip: add lazy, conditional questions

* wip: Add RSC questions

* wip: add component's lifecycle

* wip: add dependency array question

* wip: add comment and state

* chore: add more questions

* wip: add list question

* wip: add directive questions

* fix: conventions and examples

* wip: add custom hook question

* wip: add hydration question

* wip: add error boundary example

* wip: add strict mode question

* wip: investigating slow react app

* Update src/data/question-groups/react/react.md

* Update src/data/question-groups/react/react.md

---------

Co-authored-by: Kamran Ahmed <kamranahmed.se@gmail.com>
2023-09-22 05:02:12 +01:00

1.4 KiB

Custom hooks are a mechanism for code reuse in React and allow you to extract component logic into reusable functions. Custom hooks can be used to share logic between components or to abstract away complex logic to make components more readable.

Let's look at an example of a custom hook that return network status information:

Creating a Custom hook

Custom hooks are named with the prefix use and can call other hooks if needed. They can also accept arguments and return values.

import { useState, useEffect } from 'react';

function useNetworkStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    function handleOnline() {
      setIsOnline(true);
    }

    function handleOffline() {
      setIsOnline(false);
    }

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

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

  return isOnline;
}

The custom hook above uses the useState and useEffect hooks to track the network status of the browser. It returns a boolean value that indicates whether the browser is online or offline.

Using a Custom hook

function NetworkStatus() {
  const isOnline = useNetworkStatus();

  return (
    <div>
      <p>You are {isOnline ? 'online' : 'offline'}.</p>
    </div>
  );
}