Table of contents
What are React Hooks?
React Hooks is a new concept that came along with React version 16.8. They provide a way for Function Components to have some of the features that Class Components have, such as State and Lifecycle methods.
Before Hooks, there was no way to use State inside Function Components, and, if you had to use it, you had to rewrite your Component and implement it as a class.
Why use React Hooks
Before Hooks, there was no way to use State inside Function Components, and, if you had to use it, you had to rewrite your Component and implement it as a class. This brought in a lot of boilerplate code. With Hooks we can use State inside Function Components. They also provide a way to hook into Component’s Lifecycle, and have Context and Refs inside Function Components. Hooks also make your code cleaner because they reduce nesting that was previously made by Higher Order Components or Render props.
Some of the problems that Hooks solve are:
- Reusing stateful logic - by creating custom Hooks
- Having State and Lifecycle inside Function Components
- Having Context and Refs inside Function Components
React Hooks Tutorial
To get started with React Hooks, first make sure that you are using React version 16.8 or above. Open package.json file and check if both react and react-dom versions are 16.8 or above.
The useState Hook allows you to have the state inside a Function Component. This Hook is a part of the core React Library so we import it from react:
Once imported, we can call it (notice: Hooks are functions). The syntax for calling useState is:
We can pass an argument to useState Hook. This argument represents the State’s initial value. Unlike State inside Class Components, State inside Function Components doesn’t have to be an Object. It can be a string, for example.
useState returns a pair of Values:
- The first value in a pair represents the current value of the state
- The second value in a pair represents a function that we can use to change the state
A convenient way to assign values returned by Hooks is by using Array Destructuring:
is equivalent to:
useState Hook Example
In the following example, we will call useState hook and pass it the initial state. When the user clicks on the button, the value of the state changes by calling setState and passing the new value.
If we were to have multiple attributes inside the initialState object and update only the exampleAttribute, we would see that other attributes would change the value they had and become undefined. The function that changes the state doesn’t merge the previous with the new, like the setState in class Components did. If we want to preserve all of the values inside an object, we need to manually pass those values to the new state. The easiest way to do this is by using spread operator:
Multiple useState Hooks inside a component
We can have multiple useState Hooks in the same component, unlike the single state object we had in class Components. The state value doesn’t have to be an Object. We will split the state from the previous example into multiple useState Hooks:
UseEffect Hook provides a way to hook into Component’s Lifecycle. UseEffect is called after each render, including the initial render.
This Hook can have the same role as:
This Hook is a part of the core React Library so we import it from react:
Once imported, we can call it. The syntax for calling useEffect is:
The first argument (the effect) is a function that will be executed each time the useEffect is triggered. It’s advisable to use the arrow function because it will always create a new function and make sure that we don’t access any stale values. The fact that it is named after the side-effects, or short “effects“ implies that the useEffect Hook is used to cause side-effects. The return value of the effect is the function that will do the clean up of the side-effect if needed (e.g. clear interval). This cleanup function will be called before next render. The idea of useEffect is to set an effect and then clean it up before the next render and replace it with the new effect. The cleanup function will also be called on component unmount, thus behaving like componentWillUnmout.
The second argument is optional and represents an array of values that the effect subscribes to. Updating any of these values will trigger useEffect Hook and execute the function passed as the first argument. If the second argument is omitted, useEffect will run the effect after each render. If the value of the second argument is an empty array, useEffect behaves as componentDidMount – it will be called only after the initial render.
useEffect Hook Example
In the following example there is an input field for username value. Each time the input value changes, changeUsername handler is called and username value is updated. When the username value is updated, useEffect is triggered. If you follow what’s being logged into the console, you will see that ’useEffect cleanup’ is logged after each change.
With useContext Hook we are able to consume values provided by Contexts within Function Components.
This Hook is a part of the core React Library so we import it from react:
Once imported, we can call it. The syntax for calling useContext is:
The argument passed to useContext is the value returned by React.createContext. Make sure you are passing MyContext and not MyContext.Provider nor MyContext.Consumer.
The value returned by the useContext Hook is the current value stored inside that Context. If the value inside the Context changes, the valueFromContext will reflect the new value.
useContext Hook Example
In the following example we will create ThemeContext with the default value ’dark’ and consume that value inside a Function Component using React Hooks.
First Create Context
Then inside a Function Component import that Context
Rules of Hooks
As we’ve seen in useState section we can call multiple Hooks in the same Component. But, there are some rules we need to follow to do so.
First Rule of Hooks
Hooks can be called only at top-level. This means they cannot be called inside loops, conditions or nested functions. If Hooks are called at top-level we ensure that they are always called in the same order. React relies on this call order, because there is nothing except the call order that lets React know which state corresponds to which useState call. We don’t pass any key or anything similar to let React know which state is connected to which useState call. So, if we had three useState calls and put the second call inside a condition, and make that condition false after the first render, the state from the second useState will now correspond to the third State. This is not the desired behavior. If you need conditions, you can put them inside a Hook.
Second Rule of Hooks
Hooks can be called only from React Function Components and from Custom Hooks. If we tried to call a Hook from the Class Component we would get an error and wouldn’t be able to do so.
Creating a Custom React Hook
Let’s start with an example of what we’ve already learned. We will have one input field and add useEffect Hook that will run validation for that field. We will add a constraint that the username cannot contain a dollar sign.
If we want to have the same validation for other input fields, we can extract the validation Part to a Custom Hook.
- Create a file useValidation.js inside src/hooks directory
- Create a function inside this file named useValidation and export it as default (Hooks are Functions, which means they can have parameters and a return value)
- Import this function inside the Example Component
- Add a parameter to the useValidation function named value
- Move Validation Logic from Example Component to useValidation Hook
- Rename username to value
Now we can have Validation logic inside multiple Components and also call it multiple times inside the same Component.
React Hooks vs. Classes
React Hooks provide a way to have some functionality that was only available in class Components before. React Hooks can’t completely replace classes, at least not yet. And, even if they do become able to replace classes, in the official React Documentation it states: “There are no plans to remove classes from React”. Hooks are backwards compatible, which means you can add them to your project without breaking functionality.
With Hooks we are now able to have State inside Function Components. We can also hook into Component’s lifecycle using useEffect hook.
The Lifecycle methods that have equivalents with Hooks are:
- static getDerivedStateFromProps()
The Lifecycle methods that don’t have equivalents with Hooks yet are:
- static getDerivedStateFromError()
We can also use Context and Refs inside Function Components now. UseContext Hook is equivalent to Context Consumer from class Components. The syntax for useContext is simple and it doesn’t add nesting to your code. It makes code a lot cleaner.
Hooks are definitely worth giving a try. They reduce nesting and make your code cleaner. They also cut down development time if you have written a component as a function and realized afterwards you need state inside your component. You no longer need to rewrite the component as a class. You can simply use the state inside Function Component.
Since Hooks are a new concept in React, some third-party libraries don’t have support for them yet. Even React-Redux is still in experimental phase with Hooks. But, I believe they will become a preferred way to write your components soon, so start learning them on time.
Latest blog posts
Intent classification: understanding text with the powe...
In today’s world, with the expansion of data generated from various sources, analyzing it has become a critical challenge for businesses. Read more about how intent classification of textual data works and how it can lead t...
What Is Stable Diffusion and How Does It Work?
For the past few years, revolutionary models in the field of AI image generators have appeared. Stable diffusion is a text-to-image model of Deep Learning published in 2022. Find out the reasons why Stable diffusion gained ...