Refactoring the Authentication Flow Code

The authentication flow is working like a charm, but we have some repeated code in our project.

Instead of repeating the same code across the code base, we can follow the don’t repeat yourself (DRY) rule. For example, we use the same code to store tokens and user information for the LoginForm and RegistrationForm components. In this lesson, we’ll write a custom React Hook to handle this logic, but before doing that, let’s go over what a Hook is.

What is a Hook?

Hooks were first introduced in React 16.8, allowing developers to use more of React’s features without writing a class. An interesting example of a React Hook is useState.

The useState Hook is a replacement for setState, used inside functional components to manage the internal state of a component. In LoginForm, we used useState to handle the form values. We also used useState to set the message error if the login request returns an error. For a simple test, go to the login page and enter the wrong credentials, and you’ll likely get a similar error to this:

Get hands-on with 1400+ tech skills courses.