React hooks are a notoriously confusing part of using functional components. While class-based components have certain built-in features thanks to deriving from the React.Component
class, functional components have to “hook into” these features.
In the previous article, we learned about props in React. In this guide, I’m going to explain what react hooks are, and how to use them in your functional components.
For the official explanation of hooks, you can check the React docs. But be aware that their explanation isn’t near as good as the one I’m about to give you (wink wink).
Prerequisite Knowledge
What Are React Hooks?
If you’re familiar with class components, then you know that features such as state and render effects are built into it. For state in class components, all you need to do is use this.state
. To create a render effect, class components have lifecycle methods such as componentDidMount
.
Functional components do not have these features built-in like class components do. This is because unlike classes, which can derive from React.Component
, functional components cannot “derive” from anything. They inherit no functionality from the React library.
In a sense, React features such as state are features that we need to “hook into.” This concept is visualized below:
So how do we hook into these features in a functional component? We do it with — you guessed it — React hooks.
For example, useState
, useEffect
, and useContext
. state, (render) effects, and context are all features of React that are not built into functional components.
How to Use React Hooks
It’s important to realize that a React hook is nothing but a JavaScript function.
Let’s look at useState
for example.
To use React state in functional components, first import the useState
hook:
import { useState } from 'react';
The useState
hook accepts the initial state and returns an array containing the state variable and a function to set the state. Hooks are meant to be called inside of a functional component.
import { useState } from 'react';
const MyComponent = () => {
const [state, setState] = useState({});
};
And just like that, we can use state in our functional component! This is essentially how all React hooks work: we import a function and call it, which gives us access to the “hooked” feature!
Since we explored the useState
hook in greater detail in my article on state in functional components, in the next article we are going to look at useEffect
, a hook that allows us to create render effects in React.
2 thoughts on “What Are React Hooks? | React Tutorial for Beginners”