Introduction to React Hooks
Learn how React Hooks in functional components look different from a React class component.
We'll cover the following
Welcome back!
During the introduction to React Hooks, code examples will not be provided. Instead, diagrams are provided to help you visualize how React Hooks are different from existing React components.
A functional React component
Functional React components are the simplest React components. Functional React components do not hold an internal state. They are often referred to as “dumb” components.
Functional components are “pure functions” that accept props as input and return UI code in the form of JSX.
The following diagram shows an overview of a functional React component.
A class React component
Class components allow you to create stateful logic in React components. It also allows you to use lifecycle methods for side effects. For example, when the component mounts, initiate an API request using componentDidMount
.
Until React 16.8, developers always needed ES6 classes to maintain the internal state in React components and to properly utilize lifecycle methods.
With React Hooks, this will change.
Enter React Hooks
React Hooks API is available in React 16.8+.
React Hooks allow you to create stateful logic in functional React components.
This means you do not need to use ES6 classes for the same. This is particularly exciting because functional components provide better code composition than classes.
The following diagram first shows that you can maintain local state with hooks and also have side effects as required.
Secondly, the flow of the code execution is much more linear and easier to read.
In the upcoming lessons, React Hooks will be explored in more detail.