How to prevent unnecessary re-renders in React?
Here are several strategies to prevent unnecessary re-renders in React:
-
Use React.memo for components
It ensures that functional components only re-render when their props change. -
Use useMemo and useCallback hooks
useMemo
caches the result of expensive calculations.useCallback
caches function references, avoiding function recreation on every render.
-
Avoid anonymous functions and objects in JSX
Passing inline functions or objects creates new references each render. Instead, define them outside or memoize. -
Key props efficiently
Ensure that lists use stable, unique keys to prevent unnecessary re-mounts. -
Split large components
Break big components into smaller ones, so that only parts of the UI that need updating re-render. -
Use pure components (PureComponent or React.memo)
They perform shallow comparison of props and prevent re-renders if props are unchanged.
Example using useCallback:
const handleClick = useCallback(() => { console.log('Button clicked'); }, []);
This ensures handleClick
doesn't get re-created unless its dependencies change.