React hooks for functional components

Hooks in React: A Beginner’s Guide.

Introduction to Hooks

Hooks are built-in functions introduced in React v16.8 that allow React developers to use state and other React features, such as lifecycle methods, in functional components. 

Before React v16.8 was released, developers could only manage state and lifecycle with class components. However, with the introduction of Hooks in v16.8, developers could utilize state management and other React features within functional components, empowering them to apply functional programming principles in React. 

If you are a React developer and don’t like using class components, then Hooks is here to help you. 

This article provides an overview of Hooks based on my own experience. Keep reading to learn more about Hooks and discover how we’ll start using them in our applications.

By the end of this tutorial, you will have a good understanding of React Hooks and how they benefit you.

Benefits of using Hooks.

React Hook offers a lot of benefits. They do not replace your knowledge of React concepts; they provide a more direct API to the concepts you already know, like props, state, lifecycle, context, and refs. It also offers a powerful way for you to combine them.

Here are some benefits of using Hooks in your React projects:

  • Code Readability: Hooks enable you to write cleaner and more readable code in functional components without sacrificing any of the features that class components offer. 
  • Simpler and shorter syntax: Hooks simplify your codebase, eliminating the need for class components, which often require more boilerplate code and can be more difficult to read and understand. 
  • Code Reusability: Hooks allow you to extract and reuse logic across several components. Custom Hooks allows you to reuse logic across multiple components easily without changing your component hierarchy.
  • Better Separation of Concerns: With Hooks, you can split one component into smaller functions based on what pieces are related, rather than forcing a split based on lifecycle methods
  • Effective Management: Hooks allows you to manage related code effectively. You can use various hooks inside a single component to handle distinct concerns individually, such as state management, side effects, and context. 

The Code snippet below shows the difference between a Class component and a Functional Component.

Example of a class component

Example of a functional component

Now take a look at these two components. You will see that functional component code is cleaner and more readable

As you can see in the video above, both the class component and functional component code can achieve the same functionality.

Basic Hooks in React

Now that you understand hooks and how they benefit you, let’s examine frequently used hooks and how to implement them.

Hooks for state management 

useState()

There are different ways to manage state in React, but one of the most common way is using the useState Hook. The useState hook allows you to handle and manage the states in your functional component, making them stateful and responsive to user interaction.


For example, you can use useState to keep track of a counter value, as you can see in the previous example. 
To use the useState hook, we will first import it into our component from the React library. Then, you can initialize the state by calling useState within our functional component. 


Now, let’s look at a simple example of how to manage the state of a favorite color. 

useState allows you to declare a state variable and a function to update it.
In this functional component named FavoriteColor, the first value in the array “color” is our current state, while the second value, setColor, is the function that is used to update our state, which is why it’s always initiated as setState.


When this component is rendered, it will display the text “My favorite color is green,” and when you click the button, the component will re-render, update the color state to blue, and display “My favorite color is blue.”

useReducer()

The useReducer hook is similar to useState for managing state. useState works well for simple and independent pieces of state, but what if your state value has complex data or is comprised of a number of related values ? Then, useReducer may help. 


For example, if you have a to-do list app that needs to keep track of the to-dos, their titles, their completion status, and other actions like adding, deleting, and filtering them? In such cases, useState might not be enough. You may end up with multiple state variables that need to be updated together or with complex logic that makes your code hard to read and maintain.

This is where useReducer comes in handy. useReducer is another React Hook that lets you add a reducer to your functional component. it is a function that specifies how the state gets updated based on an action. An action describes what happens and, optionally, carries some data.

Let examine how useReducer can be used to increase and decrease values

Here is the code output

As you can see, useReducer lets you organize your state logic into a single function that handles different actions
This makes your code more readable and maintainable. You can also easily test your reducer function without rendering your component.
However, it is not always the best solution for every situation. Sometimes, useState, useEffect, or custom Hooks might be more suitable for your needs.

Hooks For side effects and lifecycle 

useEffect()

The useEffect Hook allows you to perform side effects in your components. With this Hook you can handle side effects in React functional components. 
Examples of side effects are: fetching data, directly updating the DOM and timers, reading from local storage, and registering and deregistering event listeners.

In this example above, the useEffect Hook fetches data (Movie titles) from TMDB movie API when the component mounts. and the result is as seen below.

Cleanup functions

Let’s talk about how React’s useEffect cleanup function works.
Imagine that you have a React component that displays a list of items from an API just like in the image above we displayed the data (movie titles) from TMDB movie API. 


Every time the component is rendered, it fetches the latest list of items from the API and displays them to the user.


Now, if the user decides to navigate away from this component to a different part of the app, The component is no longer being rendered, so there’s no need to continue fetching the list of items from the API. However, the fetch request is still ongoing in the background.


This is where the useEffect cleanup function comes in. The cleanup function is a function that is called when the component is unmounted that’s when it is no longer being rendered. It allows you to perform any necessary cleanup tasks, such as cancelling an ongoing API request.


To use the cleanup function, you can pass it as a return value from the useEffect Hook. 
let’s examine this code example below,

The code above creates a signal when the data is fetched, the cleanup function returns from the useEffect Hook, and it calls the controller.abort() to cancel the request when the component unmounts before the fetch is complete.
This ensures your React component handles asynchronous tasks effectively. It also prevents memory leaks and bugs in your code.

Conclusions

React hooks have transformed how developers create components by providing a more spontaneous and flexible approach to managing state and side effects.

As you progress in your journey with React, mastering these hooks will empower you with optimism about the potential to build more efficient and maintainable applications.

Remember, practice is critical to becoming proficient with React hooks. Experiment with different scenarios, explore additional hooks like useCallback, useContext, useRef, etc., and stay up-to-date with the React documentation for new features and best practices. Happy coding! 

Share your thoughts