From a46a49f45d3b86ba835f91e19d4b484dbab9b5ac Mon Sep 17 00:00:00 2001 From: Arik Chakma Date: Thu, 21 Sep 2023 05:58:25 +0600 Subject: [PATCH] wip: add custom hook question --- .../react/content/custom-hook.md | 51 +++++++++++++++++++ src/data/question-groups/react/react.md | 5 ++ 2 files changed, 56 insertions(+) create mode 100644 src/data/question-groups/react/content/custom-hook.md diff --git a/src/data/question-groups/react/content/custom-hook.md b/src/data/question-groups/react/content/custom-hook.md new file mode 100644 index 000000000..92f92edb5 --- /dev/null +++ b/src/data/question-groups/react/content/custom-hook.md @@ -0,0 +1,51 @@ +**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. + +```js +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 + +```js +function NetworkStatus() { + const isOnline = useNetworkStatus(); + + return ( +
+

You are {isOnline ? 'online' : 'offline'}.

+
+ ); +} +``` diff --git a/src/data/question-groups/react/react.md b/src/data/question-groups/react/react.md index b3ca3d894..a33616beb 100644 --- a/src/data/question-groups/react/react.md +++ b/src/data/question-groups/react/react.md @@ -285,4 +285,9 @@ questions: topics: - 'SSR' - 'Intermediate' + - question: How to create a Custom hook in React? + answer: custom-hook.md + topics: + - 'Core' + - 'Intermediate' ---