Hey DEV! ๐ React is awesome, but slow components hurt UX. Here are quick tips to speed up your React apps. Letโs go! ๐
โ 1) Avoid Unnecessary Re-renders with React.memo
React re-renders components whenever their props or state change. However, sometimes re-rendering isnโt needed if props havenโt changed.
const MyComponent = React.memo(function MyComponent({ data }) {
console.log('Rendered');
return <div>{data}</div>;
});
React.memo memoizes the component and prevents re-renders when props are the same, improving performance.
โ 2) Use useCallback to Memoize Functions
Functions defined inside components are recreated on every render, causing child components to re-render if these functions are passed as props.
const handleClick = useCallback(() => {
console.log('Clicked!');
}, []);
useCallback returns a memoized version of the function, maintaining reference equality between renders and reducing unnecessary updates.
โ 3) Use useMemo for Expensive Calculations
Heavy computations inside components slow down rendering. Use useMemo to memoize computed values, recalculating only when dependencies change.
const computedValue = useMemo(() => heavyCalculation(data), [data]);
โ 4) Use Stable and Unique Keys for Lists
React relies on keys to track list items efficiently. Using unstable keys like array indices can cause unnecessary DOM updates and bugs.
โ
Always use unique IDs from your data as keys:
items.map(item => <ListItem key={item.id} data={item} />)
โ 5) Lazy Load Components with React.lazy and Suspense
Large components can slow your appโs initial load time. Split your code using lazy loading to load components only when needed:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
โ 6) Avoid Inline Functions and Objects in JSX
Defining functions or objects inline inside JSX creates new references every render, triggering unnecessary re-renders.
Instead, memoize functions with useCallback and objects with useMemo.
๐ Thatโs it! Use these React tips to speed up your apps. Whatโs your top optimization? Share below! ๐๐ฌ
Top comments (0)