wasAsked.

difference between usememo vs usecallback, usestate vs useeffect

PwC · Full Stack Developer · technical

Published

Year not specified · React

Community answers

Posted by wasAsked editorial collection

useMemo vs useCallback Both memoise values between renders and recompute only when their dependencies change. - useMemo caches the result of a calculation: const filtered = useMemo( () => products.filter(p => p.name.toLowerCase().includes(search.toLowerCase())), [products, search] ); Use it for expensive computations, or to keep an object or array reference stable when it is passed to memoised children or used in effect dependencies. - useCallback caches a function itself: const handleSelect = useCallback((id: number) => setSelectedId(id), []); <ProductList onSelect={handleSelect} /> // ProductList wrapped in React.memo Use it when passing callbacks to memoised child components, or when a function is a dependency of useEffect. Relationship: useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Do not memoise everything: memoisation has a cost and makes code harder to read. Use it where profiling shows unnecessary re-renders or expensive calculations. The React Compiler (stable in 2025) can apply memoisation automatically, reducing the need for manual useMemo and useCallback in projects that adopt it. useState vs useEffect They have completely different purposes. - useState stores data that changes and causes re-renders: const [count, setCount] = useState(0); - useEffect runs side effects after rendering, synchronising the component with external systems: fetching data, subscriptions, timers, DOM APIs, logging. useEffect(() => { const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id); // cleanup on unmount or before re-running }, []); // dependency array controls when it re-runs Effect dependency rules - [] runs once after mount (twice in development Strict Mode to surface missing cleanups). - [a, b] runs when a or b changes. - No array runs after every render. Common mistakes - Using useEffect to compute derived data (setFullName(first + ' ' + last)) — instead compute during render or with useMemo. - Missing dependencies, causing stale values (follow the eslint-plugin-react-hooks rules). - Forgetting cleanup, leading to memory leaks or duplicate subscriptions. - Fetching data in effects without handling race conditions; libraries like TanStack Query are often a better fit. Summary: useState holds data; useEffect reacts to changes by doing side effects; useMemo caches computed values; useCallback caches functions.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics