Hooks are functions that allow "connecting" React capabilities to functional components (without classes). Introduced in React 16.8.
Simple analogy: Imagine your component is a robot. Hooks are modules you connect to the robot:
Main hooks:
1. useState — "Memory" Allows storing and changing data that updates the interface.
1const [count, setCount] = useState(0); // Initial value: 02return <button onClick={() => setCount(count + 1)}>{count}</button>;
Important detail: setState batches updates. Multiple setCount calls in the same event handler are combined into one re-render for performance.
2. useEffect — "Reaction to changes" Executes code after render (data loading, subscriptions, timers).
1useEffect(() => {2 fetch('/api/data').then(res => setData(res));3 return () => cleanup(); // Cleanup function4}, []); // Empty array — execute once on load
Dependency array rules:
[] — runs once on mount.[dep1, dep2] — runs when any dependency changes.3. useContext — "Access to shared data" Reads value from Context (theme, language, user).
1const theme = useContext(ThemeContext); // Got the theme
4. useRef — "Reference to DOM" Allows access to a DOM element (for example, to focus on input).
1const inputRef = useRef();2<input ref={inputRef} />3inputRef.current.focus(); // Focus on input
5. useMemo — "Caching calculations" Remembers the result of a complex calculation to avoid recalculating unnecessarily.
1const sortedList = useMemo(() => {2 return list.sort((a, b) => a - b);3}, [list]); // Recalculate only if list changed
6. useCallback — "Stable function" Remembers a function so it is not recreated on every render.
1const handleClick = useCallback(() => {2 doSomething();3}, []);
7. useReducer — "Complex state" Like useState, but for complex update logic (like Redux).
1const [state, dispatch] = useReducer(reducer, initialState);2dispatch({ type: "increment" });
8. useLayoutEffect — "Synchronous effect" Like useEffect, but executes BEFORE the browser shows the page.
Why it matters:
this binding, or lifecycle method complexity.Common mistakes:
Rules of Hooks: