Hooks the next big thing in the react ecosystem pure functions (take inputs and return output without generating any side effects) that reduce a whole lot of boilerplate you used to write with class components, and they let you share your stateful logic code between components without using the good old patterns like render props, high-order components and context api which require you to restructure your components and we all know how it tend to be a bit cumbersome and it makes your code complicated and hard to follow and if you take a look at your react app dom presentation in the react dev tools you’ll see a lot of providers, consumers, high-order components, render props and a big pile of abstractions creating the hideous wrapper-hell.

wrapper hell 🔥

With hooks you can extract your stateful logic and reuse it which makes testing it even easier, so let’s summarize some of the reasons on why you should use hooks over classes :

  • Reusing Code
  • Functional programming paradigm(Immutability)
  • Reduce Boilerplate

Personally I hate using classes in javascript, because we all know that javascript is not an oop language so classes are just syntactic sugar built on top of the prototypal inheritance model which javascript is based on, they were just added to encourage developers familiar with oop languages so they can get comfortable using JavaScript and also classes tend to not transpile very well.

Some of the hooks provided by the react api useState, useEffect, useContext, use Reducer…you can write your own custom hooks which should start with the word “use” and you can refer to other rules that you should respect when writing your own custom hooks.

Let’s write an example of our own custom hook “useFetch” that fetches data from the provided url.

custom hook useFetch

We will use our own custom hook to fetch random gifs from the famous website giphy and display them in an img tag.

display random gifs using custom hook useFetch

yeaa our custom hook works!

So we have implemented a custom hook useFetch that fetches data which can be shared between components.

Edit custom hook useFetch

That is it guys i hope you enjoyed it.

alt