Skip to content

⚡ React Performance Optimization

  • Use React.memo() for pure functional components.
  • Use useCallback() hook to memoize the functions passed as props.
  • Use useMemo() hook to memoize expensive computations.
  • Example:
const Child = React.memo(({onClick}) => {
console.log('Child component rendered')
return <button onClick={onClick}>Child onClick</button>
})
export const App = () => {
const [count, setCount] = useState(0)
const handleClick = useCallback(() => {
console.log('Clicked')
}, [])
return (
<>
<button onClick={()=> setCount(c=> c+1)}>Parent {count}</button>
<Child onClick={handleClick}/>
</>
)
}
  • ✅ Without memoization → Child re-renders every time parent updates.
  • ✅ With memoization → Child only re-renders if props change.
  • Example:
const HeavyComponent = React.lazy(()=> import('./HeavyComponent'))
return (
<React.Suspense fallback={<div>Loading...</div>}>
<HeavyComponent/>
</React.Suspense>
)
  • ✅ Load components on demand, reduce initial bundle size.
  • Use react-window or react-virtualized for rendering long lists(instead of rendering thousands of DOM nodes).

🔹 4. Avoid Expensive Operations in Render

Section titled “🔹 4. Avoid Expensive Operations in Render”
  • Move heavy computations outside render or memoize them using useMemo.
  • Keep state as local as possible.
  • Avoid keeping derived data in state(compute it).
  • Split large context(avoid re-renders of all children).
  • npm run build
  • ✅ Minified, optimized, tree-shaken.
  • Bad 👎: <Child data={{ a: 1 }} />
  • Good 👍 (useMemo): const data = useMemo(() => ({ a: 1 }), []); <Child data={data} />
HookPurposeExample Use Case
useStateLocal state managementCounter, input fields
useEffectSide effects (fetching, subscriptions, DOM ops)API call on mount
useContextShare state without prop drillingAuth, theme
useReducerComplex state logic (like Redux lite)Form with multiple fields
useRefPersist values across renders without causing re-rendersDOM refs, store timers
useMemoMemoize valuesExpensive calculations
useCallbackMemoize functionsPrevent child re-renders
useLayoutEffectSync side effects before browser paintsMeasure DOM size before rendering
useImperativeHandleCustomize ref values when using forwardRefExpose only specific methods from child
useTransition (React 18)Mark state updates as “non-urgent”Input filtering
useDeferredValue (React 18)Defer a value until less busyTypeahead search
  • “For performance optimization, I use memoization (useMemo, useCallback, React.memo), code splitting, and virtualization for long list”.
  • “React hooks give fine-grained control: useState for local state, useEffect for side effects, useReducer for complex state, useContext for global state and optimization hooks like useMemo and useCallback.