Advanced Hooks
As your React application grows, you might need more powerful tools than `useState`. The useReducer, useMemo, and useCallback hooks help manage complex logic and improve performance.
useReducer
useReducer is usually preferable to `useState` when you have complex state logic that involves multiple sub-values. It works similarly to Redux.
JavaScript
const [state, dispatch] = useReducer(reducer, initialArg, init);
useMemo
The useMemo hook returns a memoized value. It only recomputes the memoized value when one of its dependencies has changed. This is great for expensive calculations.
JavaScript
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useCallback
The useCallback hook returns a memoized version of a callback function that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality.
JavaScript
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]); Note: Don't over-optimize! useMemo and useCallback should only be used if you identify a performance bottleneck.