Introduction to Hooks
Why Were Hooks Introduced?
Before hooks, developing in React required class components to use state and lifecycle. This caused several problems:
- Complex components were hard to untangle
- HOCs and render props added complexity
- Confusing
thisbinding
Hooks were introduced in React 16.8 to solve these problems.
What Are Hooks?
Hooks are functions that let us "tap into" React features from function components. Hook names always start with the word use.
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicks: ${count}`;
});
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Rules of Hooks
1. Only Call at the Top Level
Do not call hooks inside loops, conditions, or nested functions.
// Correct
function Component() {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
}
// Wrong
function Component({ showExtra }) {
const [a, setA] = useState(0);
if (showExtra) {
const [b, setB] = useState(0); // Error!
}
}
2. Only from Function Components or Custom Hooks
// Correct: from a function component
function MyComponent() {
const [val, setVal] = useState(0);
}
// Correct: from a custom hook
function useCustomHook() {
const [val, setVal] = useState(0);
return [val, setVal];
}
Hooks You Will Learn
| Hook | Main Function |
|---|---|
useState |
Manage local state |
useEffect |
Handle side effects |
useContext |
Access context |
useRef |
DOM reference or mutable value |
useCallback |
Memoize a function |
useMemo |
Memoize a value |
useReducer |
Complex state management |
When to Use Hooks vs Classes
| Situation | Recommendation |
|---|---|
| New components | Use function + hooks |
Need this binding |
Function + hooks is easier |
| Error boundaries | Still requires a class |
| Legacy code | Class components are still supported |
Hooks are the modern way to write React components. Next we will study the first hook, useState, for managing state.