React: Introduction to Functional Components & Hooks
When starting to work on my personal app, I was excited to learn about and use React Functional Components & Hooks. Hooks help you a lot because they allow you to write components exactly with the lifecycle methods that you need. Hooks also give your code a declarative layout, and yes, you will also type less. This article will help you to understand functional components and hooks and see which hooks you can use in your projects.
What are Functional Components & Hooks?
React functional components are simple methods that return JSX. Originally, they were intended to be stateless, pure functions that just render HTML according to their props. Because they did not receive all the lifecycle hooks and state management capabilities of class components, they are leaner in terms of computer resources that they need for their operation.
With React v16.8, Hooks became available. Hooks add capabilities to functional components: To have state, to access the location or history, to access the redux store, or (simplified) lifecycle methods. Basically, they are functions that are called inside the functional components’ declaration. Let’s take a look at an example.
Example: useState Hook
The useState hook is the most widely used Hook.With it you add local state to a functional component. Consider a button that has a toggle
state. Here is the code:
1 import React, {useState} from 'react';
2
3 function Button() {
4 const [toggle, setToggle] = useState(false);
5
6 return (
8 <>
7 <input type="button" onClick={() => setToggle(true)}>Toggle</input>
8 <p>Button is clicked? {toggle}</p>
9 </>
10 )
11 }
Lets walk through this example:
- In line 1, we import the hook
- In line 4, we use the hook.
- Hook statements always have two variables: One holds the state, the other is a function to set the state. We define the variables
toggle
which holds the value, and we define asetToggle()
function to change this value. - We set the initial state of
toggle
to befalse
- Hook statements always have two variables: One holds the state, the other is a function to set the state. We define the variables
- In line 7, we define a
<button>
that usessetToggle()
for itsonClick
prop
You can see how easy it is to add state to functional components.
Why should you use functional components and hooks?
Each hook provides one specific functionality to your application. They give you the following benefits:
- Cleaner syntax: Class components need explicit
this.bind
declarations for functions that are called within the JSX code, and also when accessing props or state. In functional components, every function declaration will be inside the scope of the component, giving you access to the props and other functions without usingthis
. - Declarative Syntax: When you are familiar with hooks, you can take a quick look at the hooks a functional component uses and get a picture of the functionality it provides.
- Improved extensionality: You can write custom hooks (see below) to provide functions that you would re-implement at several parts of your application. This helps you greatly to follow the advice: Every piece of knowledge must have a single, unambiguous, authoritative representation within a system (see DRY principle).
What are other hooks?
There are many more hooks in the React eco system available, see the Hooks API Reference for a complete overview. To give you a first impression, here are other hooks that I frequently use:
useEffect
- Add side effects to your component, actions like fetching data from an external API or subscribe to an external event.useLayoutEffect
- Also for side effects, but this hook will be executed before functional components renders it’s JSX.useRef
- Define a reference to a DOM element, and use it to access the elements values.
Hooks are also available in React Redux and React Router:
useStore
,useSelector
: Access the complete global Redux store to read data, or select specific data from it.useHistory
: Access the history of your react application.
Finally, you can also define custom hooks. If you are writing similar functionality in different parts of your application, then this functionality can be extract to a custom hook. The hook itself is a functional component that exposes its values or functions as return values. To learn more, see Building Your Own Hooks.
Summary
Hooks are major milestone in React. They give functional components exactly those features that you need, like having state, defining refs, access the browser history and more. They are declarative and help you to write clean and lean code. I recommend to use hooks instead of class components for most parts of your application. You should use class components only when you need to implement complex lifecycle methods.