Better Programming

Advice for programmers.

Follow publication

Member-only story

Learn To Create Your Own useFetch() React Hook

Thomas Guibert
Better Programming
Published in
6 min readJan 7, 2020

--

Photo by Yuki Dog on Unsplash

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>
);
}

--

--

Thomas Guibert
Thomas Guibert

Written by Thomas Guibert

Frontend engineer by day, ☀️ Aspiring Solidity engineer by night! 🌝 — Read more from me: https://medium.com/@th.guibert/membership

Write a response