1. useState
Allows you to add local state to a functional component.
1import { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <button onClick={() => setCount(count + 1)}>
8 You clicked {count} times
9 </button>
10 );
11}
1import { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <button onClick={() => setCount(count + 1)}>
8 You clicked {count} times
9 </button>
10 );
11}
2. useEffect
Used to perform side effects in your components (like fetching data, setting up subscriptions, or manually changing the DOM).
1useEffect(() => {
2 console.log('Component mounted or updated');
3}, []); // Empty dependency array = run only once on mount
1useEffect(() => {
2 console.log('Component mounted or updated');
3}, []); // Empty dependency array = run only once on mount
3. useContext
Gives you access to context values without having to wrap your component with a Consumer.
1const user = useContext(UserContext);
1const user = useContext(UserContext);
4. useRef
Provides a way to reference DOM elements or persist mutable values across renders.
1const inputRef = useRef(null);
1const inputRef = useRef(null);
5. useMemo and useCallback
Used to optimize performance by memoizing expensive computations or functions.