Skip to content

What are React Hooks?

Are they a new, third way of writing components beyond the two we already have? Not really. Prior to Hooks, the two ways to write React components were Class components and Function Components. Hooks are a new technique for writing the Function components, not a whole new "third type" of component.

What are the main benefits of Hooks?

There's a lot of nuance to this question and the answer. Usually it boils down to three things. For one, writing a component in Hooks can often times mean a lot less code than writing the same component the old way with Classes. Another reason is because Hooks help us avoid some common bugs that we as developers would often introduce in our Class-based components. The main reason though, and the driving reason why the React Team decided to go in this direction with Hooks, is because they give us something called "functional composition". In other words, they help developers write better abstractions for re-usable code than the options we had before.

So now there's a new way and an old way?

In React, the most fundamental building block we have is called a component. As stated before, historically we've have two ways of creating components -- with classes or with functions. Any given project could have a mix of class-based and function-based since they're meant to work together. But the class-based components had a lot more capabilities in terms of what React features they could use. The function-based components were created with less abilities but were easier to write. Even though class-based components could do more React things, they had some limitations that made them difficult composing re-usable behavior -- something that's really important in any type of application.

The React team figured out that if they gave the function components the ability to "hook" into the whole React API similar to how class-based components could, then we could take advantage of something called "functional composition". So now we can easily compose that re-usable behavior that was more difficult with classes and function components are no longer less-capable to class components.

We have legacy React code with Classes. What should we do?

The good news is that since class-based components and function-based components were always meant to work side-by-side with each other. Nothing has changed in that regard with Hooks since Hooks are just a way to say that the function-based components