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.
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
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.
We will use our own custom hook to fetch random gifs from the famous website giphy and display them in an img tag.
So we have implemented a custom hook useFetch that fetches data which can be shared between components.
That is it guys i hope you enjoyed it.