๐ Optimizing your React application for performance doesnโt have to be a daunting task. Here are 10 quick wins you can implement to ensure your React app runs faster and smoother. Each tip is accompanied by practical examples and code snippets. โจ๐
1. Use React.PureComponent
React.PureComponent
automatically performs a shallow comparison of props and state to prevent unnecessary re-renders. ๐โก๏ธ๐ก
Example:
import React from 'react';
class PureChild extends React.PureComponent {
render() {
console.log('Rendered PureChild');
return <div>{this.props.text}</div>;
}
}
function App() {
const [count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<PureChild text="Hello, World!" />
</div>
);
}
export default App;
2. Defer Non-Critical Assets
Load assets like images or videos lazily to improve initial load time. ๐ธโณ๐
Example:
import React, { Suspense } from 'react';
const LazyImage = React.lazy(() => import('./ImageComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyImage src="large-image.jpg" alt="Lazy Loaded" />
</Suspense>
);
}
export default App;
3. Use React.memo
for Functional Components
Prevent re-renders of functional components by wrapping them with React.memo
. ๐ง โ๏ธ๐ป
Example:
import React from 'react';
const MemoizedComponent = React.memo(({ value }) => {
console.log('Rendered MemoizedComponent');
return <div>{value}</div>;
});
function App() {
const [state, setState] = React.useState(0);
return (
<div>
<button onClick={() => setState(state + 1)}>Update State</button>
<MemoizedComponent value="Static Value" />
</div>
);
}
export default App;
4. Implement Code Splitting
Reduce initial load time by splitting your code into smaller bundles using dynamic imports. ๐ฆโก๏ธโจ
Example:
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
export default App;
5. Optimize Images
Use optimized image formats like WebP and leverage tools like Cloudinary or Imgix for on-the-fly image optimization. ๐ผ๐๐ฒ
Example:
<img src="https://example.com/image.jpg?auto=format&fit=max&w=500" alt="Optimized" />
6. Use a Service Worker
Cache assets and API responses using service workers for faster subsequent loads. ๐ง๐โก๏ธ
Example:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(() => console.log('Service Worker Registered'))
.catch((error) => console.log('Service Worker Registration Failed', error));
}
7. Use useMemo
and useCallback
Hooks
Memoize expensive calculations or functions to avoid re-computation on every render. ๐งฎ๐ ๐
Example:
import React from 'react';
function App() {
const [count, setCount] = React.useState(0);
const expensiveCalculation = React.useMemo(() => {
console.log('Calculating...');
return count * 2;
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<div>Result: {expensiveCalculation}</div>
</div>
);
}
export default App;
8. Avoid Anonymous Functions in JSX
Anonymous functions in JSX create new instances on every render, leading to potential performance issues. ๐ซ๐๐ง
Example:
function App() {
const [count, setCount] = React.useState(0);
const increment = () => setCount(count + 1);
return (
<div>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;
9. Use Virtualized Lists
For rendering long lists, use libraries like react-window
or react-virtualized
to only render visible items. ๐โก๏ธ๐ฅ
Example:
import React from 'react';
import { FixedSizeList as List } from 'react-window';
function Row({ index, style }) {
return <div style={style}>Row {index}</div>;
}
function App() {
return (
<List height={150} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
}
export default App;
10. Leverage react-query
for Data Fetching
react-query
efficiently manages server-state and caching, reducing unnecessary network requests. ๐๐๐
Example:
import { useQuery } from 'react-query';
function fetchData() {
return fetch('https://api.example.com/data').then((res) => res.json());
}
function App() {
const { data, isLoading } = useQuery('fetchData', fetchData);
if (isLoading) return <div>Loading...</div>;
return <div>{JSON.stringify(data)}</div>;
}
export default App;
๐ By implementing these quick wins, youโll ensure your React app is not only fast but also scalable and user-friendly. Start with these tips and watch your appโs performance soar! ๐๐ฅ
Top comments (1)
This post has some worth while reading