The Philosophy of Hooks
Hooks allow you to reuse stateful logic without changing your component hierarchy. But they come with rules.
The Dependency Array
The most common source of bugs is lying to React about dependencies. If you use a variable inside useEffect, it MUST be in the dependency array.
useMemo vs useCallback
Both are performance optimizations, but they solve different problems.
- useMemo: Memoizes a calculated value. Use it for expensive calculations.
- useCallback: Memoizes a function definition. Use it when passing functions to optimized child components to prevent unnecessary re-renders.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);