React — Hooks
What are Hooks?
Hooks are functions that let you use state and other React features in function components.
Built-in Hooks
| Hook | Purpose |
|---|---|
| useState | Add state to function components |
| useEffect | Perform side effects |
| useContext | Consume context |
| useRef | Access DOM elements |
| useReducer | Manage complex state |
| useMemo | Memoize values |
| useCallback | Memoize functions |
useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
useEffect
import { useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Seconds: {seconds}</p>;
}
Rules of Hooks
- Only call hooks at the top level
- Only call hooks from React functions
- Call hooks from custom hooks
// ✅ Correct
function MyComponent() {
const [state, setState] = useState(0);
}
// ❌ Wrong
function MyComponent() {
if (condition) {
const [state, setState] = useState(0); // Don't do this!
}
}
Custom Hooks
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;
}
// Usage
function MyComponent() {
const { width, height } = useWindowSize();
return <p>Window: {width} x {height}</p>;
}
Mini Practice
Write React code that:
- Uses useState hook
- Uses useEffect hook
- Creates a custom hook
- Follows the rules of hooks
Up Next
Next: Learn about useState hook.
Related Topics
Frequently Asked Questions about Hooks
What is Hooks in React?
Hooks is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Hooks?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hooks.
Why is Hooks important in React?
Hooks is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.