How Did We Get Here?

Programming languages are always getting better, new iterations might release new features or bug fixes, better ways to refactor or even overhaul the whole game such as Hooks did for React. Being fairly new to React myself starting with Classes, it become apparent very quick how clunky or nested it felt at time. Continuously passing State with this.State seemed to be par for the course when working in React. Or even get into something known as Wrapper Hell were in order to reuse logic developers had to traverse layers and layers of nested higher-order components. Here is where Hooks have changed the game, pushing out Classes, with logic such as bind.this, super and constructors and integrating new API’s that accesses Hooks.

Hooks, Whats Are They All About?

Hooks were introduced back at React Conf 2018 and they allow you to reuse stateful logic without changing your component hierarchy. The issue that Hooks solve are three fold, wrapper hell, giant components splitting across different life cycles and classes. The best part is that there are no breaking changes were made when Hooks were implemented. Meaning you are able to make decisions on weather you would like to use Hooks in your applications or not, without worrying about having Classes being removed. There are many different Hooks you can reference here, but I thought I would just cover the most basic one useState and compare it to a Class in React.

React { useState } vs. Classes

Those of us that are familiar with React Classes, are no stranger the boilerplate. Your typical Class for a counter…

you need all this just to get started! Here is why Hooks are revolutionary. Putting state directly into functions removes all this boilerplate code, we can get directly into what we want are components to do. We now rely on useState which takes in two arguments, first returning the initial value in state, and then using setState to have it be updated.

Now we can useState to refactor using it as a hook…

we can add on top of this base logic by adding an increment and decrement for the counter …

There you have it! the evolution of React making things simpler and solving issues is exciting to say the least. The self-awareness alone, to identify issues within the core experience and come up with creative solutions makes me want to use React more and more.

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.