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)