React Hooks

With React 16.8 we got hooks. With them we got a new way to write our components in React. While we used classes to use the lifecycle methods like componentDidMount, we can now write functional components that are much clearer and more modular. But what is a hook and what are the default hooks?

What is a hook?

As mentioned in the beginning it is an alternative to the lifecycle methods and much more. In the past, we could only access these methods through a class. This made it very cumbersome to separate logic and UI. So called Higher-Order Components have provided a remedy. But the problem with this method was that we ended up in a wrapper hell. Sometimes a component was surrounded by several wrappers and it was hard to understand how processes work.

With hooks, our logic can be easily outsourced and can be used multiple times or swapped out to NPM as a package.

Testing components

Because of the wrapper hell with HOC's and similar it was very difficult to nearly impossible to test components. With the hooks we get the possibility to split these components and separate our UI from the logic. This gives us partly Pure Functions that can be tested very easily and partly clear logic that can be tested with little effort.

The end of classes?

Do hooks mean that there will be no more classes in React? No! The team around React has decided that the classes will not be removed for the time being. This way it is not necessary to refactor older code and it can continue to run as usual. I recommend that everyone write all new stuff with Hooks. Not because it's something new and fancy, but because it has a lot of advantages over classes.

What makes classes so bad against Hooks?

Classes are not bad or worse than Hooks. But classes need to be understood first. First you need to know how classes work in JavaScript and what "this" actually stands for. How do bindings work for Event Handlers etc. But classes are also bad for optimizing code which can affect the performance of our application. Minifying or hot reloading are not optimal with classes.

But enough about classes, what are the hooks and how can I use them?

All Default Hooks at a glance

Currently there are 3 Basic Hooks and 7 Additional Hooks provided by React. Here is a small list, for each hook there is a single article where I will explain the functionality in more detail.

Basic Hooks:

Additional Hooks:

Now you're gonna wonder if that's all there is to it. The answer, of course, is: No! We can also write our own hooks and use the hooks from React so that we can write completely new and custom hooks for our application. These can then be easily reused and even packaged out to NPM.