Hooks
Special functions in React that let you use state and other React features in function components without writing a class.
Overview
Hooks were introduced in React 16.8 to allow function components to have state and lifecycle features that were previously only available in class components. They make code more reusable and easier to understand by allowing you to organize logic by concern rather than lifecycle methods.
Example
javascriptimport { useState, useEffect } from 'react'; function Counter() { // useState hook const [count, setCount] = useState(0); // useEffect hook useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } // Custom hook function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { return localStorage.getItem(key) || initialValue; }); useEffect(() => { localStorage.setItem(key, value); }, [key, value]); return [value, setValue]; }
Key Points
- Start with "use" prefix
- Only call at the top level (not in loops/conditions)
- Only call from React functions
- Built-in: useState, useEffect, useContext, etc.
- Can create custom hooks