Why Hooks made React more functional

Over the past years, React has been known to manage state and lifecycle through class-based components. But ever since the announcement of Hooks API, lots of developers have been playing around with it and thinking of shifting towards Hooks as well as abandoning class-based components.

Some have even played around with it for a while and discovered some unique solutions or patterns that would allow them to be productive at shipping some features. Others have been creative and even shortening the line of code even further through functions.

So, why did Hooks made React more functional? Here are some few things you have to know:

It’s simple and straightforward

The main selling point of React Hooks was it’s very simple and straightforward without a doubt. We still get used to class-based components to manage the state and lifecycle for us. But based on my personal experience, once you try hooks, you will never look back.

Let us try to compare the two code snippets with and without using Hooks:

Without hooks

class App extends React.Component {
state = { clicked: false, initialized: false };
componentDidMount() {
this.setState({ initialized: true });
}
setClicked = () => {
this.setState({ clicked: true });
}
render() {
const { initialized, clicked } = this.state;
return (
<div className="App">
{initialized && <h1>Initialized</h1>}
<h1 onClick={() => this.setClicked(true)}>Please click me!</h1>
{clicked && <h2>You clicked an object!</h2>}
</div>
);
}
}
view raw componentClass.js hosted with ❤ by GitHub

With hooks

function App() {
const [initialized, setInitialized] = useState(false);
const [clicked, setClicked] = useState(false);
useEffect(() => {
setInitialized(true);
});
return (
<div className="App">
{initialized && <h1>Initialized</h1>}
<h1 onClick={() => setClicked(true)}>Please click me!</h1>
{clicked && <h2>You clicked an object!</h2>}
</div>
);
}
view raw componentHooks.js hosted with ❤ by GitHub

There are a couple of things we can observe here:

  1. In class, you need to initialize the state separately and call that state object in setState function. With hooks, you initialize state setter alongside a state.
  2. In class, you need to declare the lifecycle method name such as componentDidMount. With hooks, you only need to declare useEffect inside a function. Dan has stated this comparison in React Conf 2018.

This, of course will still depend on your preference and taste whether you prefer classes over functions. If you want straightforward functions to do everything for you, choose hooks. If you prefer verbosity, choose class.

It encourages us to think and design our code the “functional way”

Hooks were made with the intention of doing everything the functional way. This includes state, component lifecycle, event handling, and reusing state change just to name a few.

Since React itself were made with Functional Programming in mind, Hooks allowed us to fully immerse in Functional Programming and minimizing the use of Object-Oriented Programming in our approach.

If you’re a purist who prefers to design everything in functional programming paradigm, then this is a good news for you.

It addresses some architectural mistakes of the past, leaning towards Functional Programming

If you look at a typical React application in React DevTools, you will likely find a “wrapper hell” of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions — From React Hooks docs

If you are a seasoned React developer who has experienced the good, bad, and ugly for the past few years knows how many patterns you can make by now. These are some of the popular patterns such as Higher-Order Components, State hoisting, Render props, Container-Presentational Pattern, Spread attributes, and so on. You can use plethora of architectures that you can imagine in it.

But some of these component architectures tend to introduce some problems along the way such as callback hell or wrapper hell or unnecessary nesting that most developers encounter when reusing some logic across different components. They even admitted these problems that occurred if you checked their introductory document about React Hooks. I’ve encountered these issues firsthand and it’s not that pretty so to speak.

If anything, it’s very flexible that imagination is the limit as to how you can structure your code through React as it is following how JavaScript itself works. But, flexibility comes at a grave price and we’ve seen it time and time again as how devastating it is, let alone impact the performance as well as how we debug it.

With flexibility, it’s easy to shoot yourself on the foot which reminds me of the days of C programming language wherein it’s flexible in terms of memory management and allocation but can easily get mismanaged.

With Hooks, it solves some of the headaches we experience when architecting our React App. For instance, instead of using Higher-Order Components or Render Props, we can use Hooks to solve our problem. This effectively let us use specific architecture rather than having to use lots of them and transition between class and functions to solve specific use-cases we experienced building the app.

You don’t need to worry about “this”

One of the pain points of class-based components is you still need to determine the context of this manually and declaring super inside the class constructor. You may have problems with this such as this is an extra typing on developer experience.

Typically, if you’re not using arrow functions inside your class-based component, you will have to bind the this keyword in the functions that you’re using within the class constructor just to let your function know that it has to point to the context of class rather than the function itself just so you can set the component state. I experienced this in the past and thought that it unnecessarily waste our time binding the function that there has to be a better way to manage our state directly.

Thankfully, Hooks already solved the problem and we can now manage state inside the function!

Let us try to compare the two functionalities, one function not binded and the other one binded:

As you can see clearly from the sample, the one button which its function is not binded didn’t respond to our setState function. This is because it’s still getting the function scope rather than using the class as the scope in this keyword. Just imagine a couple of functions you need to bind if you have lots of them, it immediately turns into a nightmare.

I have to admit, I was annoyed by how cumbersome it is to declare every function of yours to bind into your class, although this was later solved when you use arrow functions instead.

Through using hooks, you no longer need to worry about it.

Is the introduction of Hooks spell the doom of Class-based and Object-Oriented Programming?

It generally doesn’t smell the doom of Object-Oriented Programming but we’re seeing a lot of benefits in using a “function-only” approach like implementing functionalities in just a few lines of code.

What generally dictates which programming paradigm you should use will ultimately depend on your use-case and it just so happen that React was intended to be designed as functional programming from the very start.

Although, I don’t see OOP will get obsolete or so for that matter. It’s just that it has been proven that Functional Programming would be less prone to errors than using Object-Oriented Programming — at least in React. This of course is debatable depending on the context of the application and your use-case.

I would like to be pragmatic than to be religious on one thing and discard the rest. No matter how succinct a Programming Language can be, it’s still prone to human errors no more no less. Choose the ones that matters to your app and don’t just simply see every paradigm as religious or dogmatic.

Conclusion

React Developers were bold enough to try out new things and it paid off. No one can argue React Hooks definitely made React much better in my opinion. The first time I started playing around with Hooks I was hooked, literally just how easy and intuitive this new pattern is although it took me a while to adopt it in my recent projects until I started leaning towards it.

For one, it’s cleaner and elegant as well as you get to use functional components to its fullest potential, effectively eliminating the bloats we have to do just to start applying some functionalities like in the case of using class-based components.

To some, it’s going to cause confusion because we got used to class-based components to manage state for us. But we have to remember that the overall design of React was intended to use functions all along so it makes much more sense to incorporate Hooks with that matter.

At the end of the day, React still maintains and holds the top contender as one of the flexible Front-End Frameworks out there. Especially with the release of Hooks, React proved once again that flexibility is a good thing.

A Software Engineer who loves to code and write articles.

Leave a reply:

Your email address will not be published.

Site Footer