React is fast, but as applications grow, they can become sluggish if performance isn’t managed. This post will go over common strategies to optimize performance in React apps, focusing on re-renders, state management, and memoization.
Avoiding Unnecessary Re-renders
One of the main causes of performance issues in React is unnecessary re-renders. Using React’s memo function or React.PureComponent can prevent this in components that only need to re-render when props or state change.
import React, { memo } from 'react';
const ExpensiveComponent = memo(({ data }) => {
console.log('Rendering ExpensiveComponent');
return <div>{data}</div>;
});
Using React's useMemo and useCallback
The useMemo and useCallback hooks allow you to memoize expensive calculations and callbacks, improving performance by ensuring these computations aren’t repeated unnecessarily.
import React, { useMemo, useCallback } from 'react';
function App({ items }) {
const sortedItems = useMemo(() => {
return items.sort();
}, [items]);
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <button onClick={handleClick}>Click me</button>;
}