Hooks to the Rescue

Let’s turn the same class component into a Hook-based component. We won’t change any functionality of the search itself but just refactor the code from class to hook syntax.

Woah! We went from 29 lines to 17 lines of code. If my math doesn’t fail me, that’s a whopping 41.3% decrease in how much code we have to write.

If we could save 41.3% time for each component, on paper, we could write our app in almost half the time. Reducing the time we need to write our app by half is overly optimistic, but it could happen. Only time will tell.

Change is the only constant in life, so let’s crack open and demystify how Hooks work.

The first thing we need to do is import the useState from the React package.

Defining our state with Hooks looks like this:

This might throw you off for a second. I know it threw me off. What are the array brackets doing in there?

The array bracket syntax is called array deconstructing assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays (or properties from objects) into distinct variables.

The destructuring assignment uses the left-hand side of the assignment to define what values to unpack from the sourced variable. Here’s an example to illustrate:

searchFieldValue is the first value, which is the initial state.

The second argument, handleSearchFieldChange , is just a function, allowing us to change the searchFieldValue state based on what we passed as the argument.

And to drive the point home.

So there we go. We’re no longer obligated to use the class-based syntax whenever we have stateful components.

Here’s how you would create the search component with React hooks: