React Hooks
Table of Contents + −
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class component.
What are Hooks?
Hooks are functions that let you “hook into” React state and lifecycle features from function components. They don’t work inside classes.
Built-in Hooks
1. useState
The useState Hook lets you add state to function components.
const [state, setState] = useState(initialState);
Example:
function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;}
2. useEffect
The useEffect Hook lets you perform side effects in function components.
useEffect(() => { // side effect code return () => { // cleanup code };}, [dependencies]);
Example:
function DataFetcher() { const [data, setData] = useState(null);
useEffect(() => { fetch("https://api.example.com/data") .then((response) => response.json()) .then((data) => setData(data)); }, []);
return <div>{data ? JSON.stringify(data) : "Loading..."}</div>;}
3. useContext
The useContext Hook lets you subscribe to React context without nesting.
const value = useContext(MyContext);
Example:
const ThemeContext = React.createContext("light");
function ThemedButton() { const theme = useContext(ThemeContext); return ( <button className={theme}>I am styled based on the theme context!</button> );}
Custom Hooks
Custom Hooks let you extract component logic into reusable functions.
function useCustomHook() { // custom hook logic return [state, setState];}
Example:
function useWindowSize() { const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight, });
useEffect(() => { const handleResize = () => { setSize({ width: window.innerWidth, height: window.innerHeight, }); };
window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []);
return size;}
Rules of Hooks
- Only call Hooks at the top level
- Only call Hooks from React function components
- Hooks must be called in the same order every render
Best Practices
- Keep Hooks focused and single-purpose
- Use custom Hooks to share logic
- Follow the naming convention (use prefix)
- Handle cleanup in useEffect
- Optimize with proper dependencies
Common Use Cases
- Form handling
- Data fetching
- Window event listeners
- Animation
- Authentication
- Theme switching