This video is available to students only

Introducing React Hooks

This module introduces us to React Hooks; what they are, how to use them, and why they're an important part of modern React development.

Introducing React Hooks#

Hooks are not the newest addition to the React library. In fact, they were introduced in version 16.8 (the current version at the time of writing is 16.13.1). However, they have taken a little while to be more widely adopted by the community as the standard practice when developing React components.

In React, Hooks allow developers to tap into some of the more powerful features of React, such as state and the component lifecycle, without having to write some of the more cumbersome syntax required in more "traditional" class-based components.

Why Hooks?#

Hooks offer us several big advantages :

  1. They allow us to write smaller, more manageable components

  2. They allow us to reuse stateful logic between components (we’ll discuss this next)

  3. They reduce the complexity of dealing with the React component lifecycle

  4. They eliminate the difficulties that learning about and dealing with JavaScript classes can bring, especially around how this works and binding event handlers.

We can cover these advantages with a couple of examples.

Reusing stateful logic#

By ‘stateful logic’ we are referring to a component’s state, the data stored by the component, and any associated logic to alter that state.

Before Hooks came along, state was quite rigidly bound to a particular component and common or repeated logic wasn’t easily removed into a separate space to be reused across other components.

Hooks solves this problem by allowing you to grab this stateful logic and create your own ‘hook’ to reuse wherever you wish, without changing your component hierarchy.

Let’s look at a quick example.

Say we wanted to know the status of a user compared with the amount of authorized roles they had within a system:

But then, in another component, we wanted to see a list of that user’s roles, perhaps for an account page. That could look like this:

As you can see, we’ve got a lot of shared logic here. We can use a custom Hook to abstract this into a shared state logic that deals with the roles list.


This page is a preview of Beginner's Guide to Real World React

No discussions yet