Why you Need Custom Hooks and How to Create Custom Hooks. (React.js)

Introduction: what is a Hook?
Referencing the documentation from the @react.js website, Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
What is a Custom Hook?
A custom hook is a unique JavaScript function whose name begins with "use" and can be used to invoke other hooks. A unique identity is not required for a custom hook.
Why You Need Custom Hooks
It saves you the trouble of reinventing the wheel.
Developers can encapsulate and reuse code within functional components by using custom Hooks in React. By breaking down complex logic into reusable parts, it encourages code reuse, readability, and maintainability.
How to Create Custom Hooks
A good example of when you need to create a custom hook is when you employ the Fetch function to get data.
Syntax Example
- Create a new component
export const useFetch(url) => {
const [loading, setLoading] = useState(true);
const [product, setProduct] = useState([]);
const getProducts = async () => {
const response = await fetch(url);
const products = await response.json();
setproducts(products);
setLoading(false);
}
useEffect(()=>{
getProducts();
},[url]);
return{loading, product}
}
}
Note:
When using custom hooks, it is pertinent you type the prefix "use" before declaring the function.
The naming convention does not have a specific signature; you could use a different name other than "Fetch". It works as long as you include the prefix "use".
The return value should contain the state values.
The useEffect hook is kept there to trigger a re-render each time the URL changes.
Usage
Now, import the component to wherever its usage is needed.
import {useFetch} from './YourfileLocation' /*Put the file location*/ const url = 'https://www.Google.com'; const Example = () => { const {loading, product} = useFetch(url); return( <div> <h2> {loading? 'loading' : 'Results' </h2> </div> ) }