Member-only story
Learn To Create Your Own useFetch() React Hook
In just five minutes
Hooks are a great utility that were added in React 16.8. They let you write stateful components without writing a class. It’s the thing I love the most about React, by far.
React comes with a lot of them — already built into the library. These include, for example, useState
, useEffect
, useContext
, and plenty more.
They’re great for a lot of general use cases, and what is even more awesome is you can create your own Hooks for your own project’s needs.
How They Work
A Hook is simply a function that will take as many arguments as you need it to and return what you want it to return to your component.
Below is an example of the simplest Hook ever:
function useYear() {
return new Date().getFullYear();
}export default useYear;
Boom, that’s it. Looks like a regular function, right?
It can be used as follows:
// ...import useYear from "./useYear";function App() {
const year = useYear(); return (
<div className="App">
<h1>Year: {year}</h1>
</div>
);
}