React Hooks
React introduced Hooks in version 16.8 to allow functional components to manage state and side effects, something that was previously only possible in class components.
🧠useState Hook:
-
The
useState
hook allows functional components to add state. -
Syntax:
const [state, setState] = useState(initialValue);
-
Example: A counter component that increments a number when clicked.
🧠useEffect Hook:
-
The
useEffect
hook lets you perform side effects like data fetching, subscribing to events, and manual DOM manipulation. -
Syntax:
useEffect(() => { /* effect */ }, [dependencies]);
-
Example: Fetching data when a component mounts.
🧠useMemo Hook:
-
The
useMemo
hook is used to memoize values, which helps optimize performance by preventing unnecessary re-calculations of expensive calculations. -
Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
In short:
- useState is used to manage state.
- useEffect handles side effects in a component.
- useMemo helps with performance optimization by memoizing values.