React Hooks were introduced in version 16.8, allowing developers to use state and other React features in functional components. They replaced class components and simplified stateful logic sharing. Let's review the essential hooks.
1. useState
Declared state in functional components. It returns a tuple containing the current state value and an updater function.
const [count, setCount] = useState(0);
2. useEffect
Handles side effects (data fetching, subscriptions, timer setup). Its dependencies array governs when it re-runs:
[]: Runs once on mount, cleans up on unmount.[dep1, dep2]: Runs on mount and whenever the dependency values change.- No array: Runs on every single render.
3. useMemo and useCallback
Performance optimization hooks:
useMemo: Memoizes the *result* of an expensive calculation.useCallback: Memoizes the *function instance* itself to prevent unnecessary child rerenders.
const memoizedValue = useMemo(() => computeExpensiveValue(a), [a]);
const memoizedCallback = useCallback(() => doSomething(b), [b]);
Rules of Hooks
To avoid rendering bugs, you must follow these two strict rules:
- Only call Hooks at the top level: Do not call hooks inside loops, conditions, or nested functions.
- Only call Hooks from React functions: Call hooks from React functional components or custom hooks.