React Hooks

A new feature from version 16.8.0, one of the most hyped topics as 2019 kicks off.

Fish hook via AntanO

What is React Hook?

React Hook is a feature that allows you to use state and other React features without the necessity of writing a class. With React Hook you’ll be able to:

  • Execute functions when the component is mounted and when dismounted
  • Add to context API more easily to reflect the changes in a functional component
  • Create your own abstractions that play with the lifecycles of React and use them as functional components

Why were Hooks made?

Hooks were intended to resolve three problems that frequently occurred, in the language Javascript as much as in the React lib.

First motive: It’s hard to reuse logic between components.

If you already use React you’ve probably noticed that you have to repeat yourself nearly a thousand times in order to duplicate logic, such as connecting to a state provider (connect in Redux for example).

Second Motive: Complex components end up being difficult to understand

Imagine that you have a complex component that deals with things that aren’t related to your component. For example, your component needs to initiate three timers that work at different times and also has to stop these timers when the component is done being assembled.

Third motive: Classes confuse.

Javascript constructs prototype-based classes, meaning that classes in Javascript don’t work the same way as the majority of the languages we see on the market like Java, C#, Ruby…

How do they resolve these problems?

Now that the problems we run into have been made clear, we’re going to take a look at how Hooks solve these problems.

Should I use hooks?

Definitely! You don’t need to refactor all your classes to change your entire codebase, especially if you don’t already have tests, then it really wouldn’t be a good idea. Since Hooks can coexist with classes, it’s not a problem if your new components use classes and the old ones stay as classes.

Creditas Tech

Our technologies, innovations, digital product management…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store