Sitemap

React Hooks

6 min readFeb 13, 2019

--

If you are familiar with the current React framework from Facebook, you may have heard news of the feature soon to be released by “the Captain,” Dan Abramov: hooks. According to the React Documentation, hooks will allow for the use of state and other features without the need for those pesky classes and lifecycle methods. But are classes even that bad? What is the motivation behind introducing this feature that may reduce the need for another?

If the thought of using hooks in place of classes scares you, don’t panic just yet. The React team is implementing a gradual adoption strategy in which “hooks work side-by-side with existing code so you can adopt them gradually.” Hooks are still experimental and React advises against refactoring your apps to implement this new API framework without first easing in. So even if you can’t wait to start using them, Hooks will work perfectly well with your already implemented code. Take it from the top:

At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.

On the other hand, if classes and lifecycle methods have you tearing your hair out, you may be in luck.

React programmers have identified a number of compelling reasons for the transition:

  1. Reusability: It can be difficult to reuse stateful logic between components.

While render props and higher-order components attempt to “attach” reusable behavior to a component, hooks may provide an alternative to the clunky, obscure restructuring associated with these features. Programmers should be able to test and share stateful logic between components without changing their app’s hierarchy. Enter hooks to solve the problems associated with enormous components, duplicated logic, and complex patterns.

2. Organization: As components become more complex, they are also harder to understand.

While simple components are easy to maintain, when they become multi-faceted and logic is distributed between lifecycle methods and other components, it can lead to bugs, side effects, and chaotic code. As it is now, unrelated code may often be held within the same methods, lifecycle methods tasked with fetching and updating may also attempt to establish event listeners, and destructuring and testing become burdensome. Hooks, however, will allow for components to be split into more manageable functions, thereby reducing the need to combine responsibilities under one method.

3. Simplicity and Optimization: React has a steep learning curve.

In an effort to stay relevant and learnable, React is also seeking to trend away from classes in order to reduce the barrier to wider implementation. While you may be perfectly comfortable working with props, state, and the tree-like structure of React, the differences between class and function components, let alone the intricacies of how this works in Javascript as compared to other languages, can still confuse even the most experienced coders. React developers believe the “de-emphasis” of classes will both improve the digestibility of React as well as optimize the framework. Abramov claims hooks will reduce not only the number of concepts you need to learn but also the bundle size of your code. Hooks, they claim, “let you use more of React’s features without classes.”

So, how does it work?

The State Hook

Get Chris Benedict’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s look at how we can accomplish the same task without classes as we can with them. Consider the following basic form:

Press enter or click to view image in full size

You are probably most familiar with the structure and syntax of the example below in which we (1) create a class named “Form,” (2) set initial states equal to empty strings using the constructor function, and (3) re-set that state with this.setState() as information is entered into the form.

And this is fine for all intents and purposes, but could it be better? Well, as your code (and your app) becomes more and more complex, you add feature upon feature, you connect different class and function components through various levels of abstraction, and any number of programmers are brought into the equation, perhaps the value of hooks begins to reveal itself.

If we look at the function component below, which accomplishes the very same job as our class component above, we should make note of the new features of React 16.8.

First, useState() allows us to add state to function components and access it locally. Before hooks, a function component would have to be converted into a class component in order to make use of state because where we can set state with this.state in a class component, function components do not have access to this. With hooks, useState() is able to declare state variables (passing it an initial value) in the same way as this.state in order to share these values between functions. Better yet, state does not have to be an object, as it does with classes, which means we can initialize “state variables” with numbers or strings as well.

But why do we create two constants (toppings and setToppings, for example) above? Simple. By initializing const toppings = “ ”, we can store this value and access it later; and when we want to update our toppings, setToppings is there to help, rather than the old this.setState function. In other words, the useState hook returns both the current state and a function used to update it when we click our button. Maybe even more exciting, we can now use our “ state variables” by name (toppings vs. this.state.toppings).

React is already getting more digestible with just useState, but that’s not all hooks can do.

The Effect Hook

The Effect Hook lets you perform side effects in function components.

The side effects the React team is referring to here include operations that happen in React components like data fetching and manually changing the DOM, typically performed with componentDidMount, componentDidUpdate, and componentWillMount. Because we want side effects to occur after the render method, we usually stick them inside these lifecycles methods, but that means we will have to write duplicate code in many cases. This happens because we often want the same thing to happen whether the component has mounted or has been updated.

However, with the useEffect method we are asking React to perform certain tasks after rendering, which it will remember and perform again during updates. This can eliminate the need for both componentDidMount and componentDidUpdate. and when we place the useEffect method inside of our function component, we can access the state variables as well.

If you’re grasping any of this, congrats! If not, no worries! Once again, Hooks are slowly being rolled out by the brains at Facebook, and you can always refer back to the documentation for guidance. My point, rather than trying to breakdown all of the comprehensive docs, is to introduce the concept of Hooks and why we, as React developers, can look forward to a (hopefully) seamless transition that will make our lives easier. All this to say, the potential for Hooks to simplify React looks promising and let’s hope the barrier to grasping these concepts isn’t too high.

For more information, check out these killer sources:

--

--