I think it's fair to say that when it comes to Hooks, you'll find three types of React developers: love the idea, hate the idea, and just confused about the whole thing.
If you are one of those wondering what noise is, this article will give you much needed relief.
So grab a coffee, lean back and enjoy!
Rapid changes and overnight tectonic shifts don't bother front-end developers. They figured out that resistance is futile and set out to learn a new CSS Framework every year, a new JavaScript Framework every week (because that's how quickly they seem to proliferate), and complete rewrites of personal and business web applications. every two years.
And yet, no one was prepared for the mammoth change Facebook's React team made with Hooks. Suddenly, React developers were being told that the old way of building apps with classes was not the best idea; and that they should now embrace this brilliant, new, highly capable thing called Hooks.
On whether everyone should rewrite their React app's classes as Hooks, the React core team dissuaded them, arguing it was too much effort. But they're really pressed for the idea that class-based components go into maintenance mode, and Hooks are the bright new future that everyone wants.
It left everyone scratching their heads. The hooks had a non-trivial area to cover, the mental model was turned upside down, and the learning curve (with many “surprise!” Moments) was steep. At the time of writing, 18 months after release, Hooks are more or less becoming a standard in React apps. Knowing them is a must for new developers (like, unfortunately, knowing about class-based components as they are used in many newer / old projects).
But the general scene remains unclear; those who understand a little hooks have declared themselves "experts", while the others grope in the dark. Among senior developers, almost all see Hooks as a much better solution, while a few say they are just one more weapon in their stash.
The crux is that the winds are blowing in the direction of Hooks and whether you like them or not, you would make your career a major boost by understanding them. Now let's get to understand two basic things about Hooks: 1) what they are; and 2) why you need it.
However, I feel I have to underline the flow of this article.
Normally it would make sense to tackle the “ what ” issue of something new and only then move on to “ why .” However, as this is an article for confused React developers (or just for developers front-ends in general), I think it is much more important to approach the problem by explaining the type of problems that Hooks solve. That done, the tension in our minds will be dissolved, and we will know the philosophy and the pragmatism behind Hooks. And then, convinced of the idea (or not, although that won't help much if you want to become / stay a React developer), we can go through an overview of what Hooks are.
Why were React Hooks created?
Hooks weren't created just because brilliant Facebook engineers were getting restless. You see, React is something that Facebook uses itself (and very heavily too), so from day one they looked to evolve React in the direction that best meets their needs (composable interface work and high performance). After writing and maintaining tens of thousands of components, the React team decided that class-based components didn't work.
Let's take a look at various reasons (highlighted by Facebook and others) that caused developers to dislike class-based components.
JavaScript classes are a lie.
This is my personal complaint about the direction of the basic language. JavaScript may sound like a C-inspired curly brace language, but that's where the similarity ends. But then, the ES5 / ES6 version of the language tackled the "classes". Suddenly, “modern” JavaScript code made developers of other languages feel right at home:
class ShoppingCart extends BasicShoppingCart { constructor(items) { super(items); this.items = items; } getTotalPrice() { let price = 0; for (let item of this.items) { price += item.price; } return price; } // and so on }
Classes, subclasses, inheritance hierarchies, constructors, getters, setters, static members (roughly speaking), les, extends
and new
keywords - stuff that gives hardened OOP architects mental orgasms (with all due respect to their experience and capabilities). Just as pasting "Java" into the name of the language (in its early days, when it was called LiveScript) worked like a brilliant marketing stunt, perhaps the keyword "class" was meant to strengthen the position and blend in with the crowd of languages which are very similar to each other (PHP, Perl, Python, Ruby, Java - you can make an almost seamless transition from one to the other).
But classes are a lie (of the "damned" type) in JavaScript. When a JavaScript engine executes code, it has no notion of classes; thus, a tool like Babel is needed to convert "modern", "pretty" classes into simple functions. If there is inheritance involved, it is converted to only. type of inheritance possible in JavaScript - Prototypical inheritance .
So when we close our eyes and write class-based code, we are lying to ourselves and weakening our position for the day our superficial knowledge will bite us.
Well, precise is tricky!
Despite the brave attempt to hide the fundamental keyword this
in JavaScript, the problem often arises in React classes (and JavaScript classes, in general, too). In several use cases, component functions generate errors because they are not tied to the correct context at that time of execution. To fix this you need to bind()
(read precise for more details) at the start of the React context explicitly, or use the arrow functions for callbacks. This is certainly not a deciding factor, but it increases the cognitive burden by adding yet another thing to be aware of at all times; and of course, that's the chasm every new React developer falls into.
Much ado about something
Reusing code is a common goal in software development . Classes can promote code reuse in other contexts (and languages), but in React, they introduce code sharing issues. This was a major point of debate / interest early on in the React world, and the community eventually developed solutions like higher-order components and rendering props to deal with it. The basic idea is that components are passed on to other components, which “wrap” certain functionality around them. Anyone who has messed around with the code using these "fixes" knows the pain and doesn't want to do it again (including me).
You just need to read the official documentation for Higher Order Components to see for yourself how cumbersome the idea is. In real-world projects, multiple pieces of code often need to be shared, which can easily result in multiple hierarchy layers of component encapsulation. This is the kind of code that even its author won't understand after a few weeks! Yes, while code reuse isn't impossible when using React classes, it is clunky and confusing.
Propeller drilling
Drilling props is the problem you face (in Vanilla React, at least) when you have a prop at the top of the component hierarchy, and it needs to be made available to a component at the bottom. Here's an example: Consider the user profile in a typical web application, which is typically displayed in the header. Now suppose the user details are needed in the footer component as well, maybe to say something like "You've done 34 transactions so far | Get more interesting statistics here ”. How do you make profile information available in the footer if you are using classes? Well, some React developers I know would say "fuck it!"
The only approach that comes to mind is also the only option: to keep passing the profile support from the component to its child component until it reaches the footer component. Yes, this is a tedious process, and yes, it makes the code hard to read (because in the middle components you have to mentally continue to ignore the prop as it has no use except just going down). This downward chain manipulation of a propeller is called propeller drilling and is a dreaded phenomenon in the React world.
When using classes, the React developers would fix it by using something like Redux, but that's too much upfront investment if you're not going to be using Redux for everything. With Hooks, React released a feature called Context that was tailor-made for this use case. Now Context can also be used with classes, but the awkwardness is hard to ignore; also, with Hooks, consuming multiple contexts is a snap.
Less to learn
It may sound counterintuitive, and the React team recognizes the point. A whole new way of writing Reaction apps are introduced; we're told that we shouldn't rewrite or throw away existing class-based code, yet the React team tells us there is less to learn!
In fact, the point is that in the short term, the overall complexity and confusion of the React ecosystem is going to skyrocket (and it is, as new people learning React have to learn Classes, HoCs, Hooks, Context, Redux and many other libraries, as well as their corner cases). But the most important point is that if Hooks turns out to be a successful concept, in the long run a lot of concepts can be scrapped, leaving us with a small core of Hooks, functional components, and not much else. other. It's not happening anytime soon (just because of the amount of class-based code out there), but that's where we'll end up.
"Upgrade" sensitive components
A common dilemma in React is deciding whether a new component should be written as a class or as a function. To minimize complexity, the common practice has been to start with a functional stateless component. Then, if a time comes when you think the component in question needs to maintain a state or needs access to more functionality (lifecycle methods, for example), you convert it to a class-based component. Except you just need to remove all the code from the component, rethink the approach, and then write a class-based version. Not fun, yes.
With Hooks, these component “upgrades” are easier and smoother: a functional component remains a functional component even after having assumed many tasks; lifecycle methods are not included in Hooks, although some similar functionality is available; finally, any common functionality can be pulled into separate hooks and reused by other components. Have you spotted the beauty in this case? - everything is either a function or a hook (which is also a function, but we can distinguish for development purposes), and there is no monkey business involved when trying to place a square peg in a round hole. 😀
So, there we have it. The brackets are not about one thing but are a major paradigm shift. It's impractical, yes, but the resulting developer experience is much better (compared to React with classes).
Now that we've covered the “why”, let's turn our attention to what Hooks really are.
What are Hooks in React?
The hooks are tough and very easy to set at the same time. The easy version is what you'll find in the initial sentences of the official documentation: Hooks are a way to write React components without classes; they also provide you with ways to 'hook up' core React functionality such as state, check-ins, etc., into functional components.
It didn't help much, right ?!
Because that didn't help me the first time around, I stumbled across Hooks. To understand what hooks really are, you have to do a long, patient study of their ins and outs (and there's no shortage of them!), Build apps using them (maybe even rebuild older apps), be bitten. by special cases, etc.
But just to give you an “impression” of it, here's what the code looks like with Hooks. Remember that all components are functional and the code for a component is defined inside.
import React, { useState } from 'react'; export function Counter() { const [count, setCount] = useState(0); return ( You clicked {count} times</p> setCount(count + 1)}> Click me </button> </div> ); }
Yes, it's the same Counter component we've all written dozens of times using classes! But you can see how drastic the differences are: the constructor disappears, accessing and changing state is much simpler and modular (you can have as many useState()
invocations as you need to handle different state elements), and the code is shorter. In many cases, the resulting code is much shorter than a class-based component - simply because Hooks capture and provide the same functionality succinctly.
There are several types of hooks, and useState()
is just one of them. If you are curious about how many there are and what they do, take a look at the official docs site .
Conclusion
Hooks are making huge changes to the React ecosystem and are here to stay. They simplify component structure, architecture, hierarchy, code reuse, and more. Although there are some extremely vocal reviews, the overall reception has been very warm and the future looks bright.
It's one of those foundational contributions of the React team that is likely to impact other frameworks and influence front-end development fundamentally.
Nikunj is a forward thinking developer at Elitech Systems, offering more than four years of experience building, integrating, testing and supporting, iOS and Flutter applications. He’s a big fan of cross-platform programming and an expert in new ways to create silky smooth iOS applications & Cross Platform applications. His framework of choice is Swift. When he is not building and scaling back end systems, you’ll find him to reading or writing on technology and photography.
Comments are closed.