Performance & Best Practices
A fast React app requires understanding re-renders, bundle size, and lazy loading. This final lesson covers the essential tools and patterns every production React developer needs.
1 React.memo & Re-render Optimization
React — Preventing Re-renders
// React.memo — skip re-render if props haven't changed
const ExpensiveChart = React.memo(function Chart({ data }) {
return <canvas>{/* heavy render */}</canvas>;
});
// Stable callback reference with useCallback
function Parent() {
const [count, setCount] = useState(0);
const [theme, setTheme] = useState("dark");
// Without useCallback: new function every render => Chart always re-renders
const handleClick = useCallback(() => {
console.log("Chart clicked");
}, []); // stable reference
return (
<>
<button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
<ExpensiveChart data={[1,2,3]} onClick={handleClick} />
</>
);
}
2 Code Splitting & Lazy Loading
React — Lazy Loading Routes
import { lazy, Suspense } from "react";
// Lazy load — each route becomes its own bundle chunk
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));
function App() {
return (
<Suspense fallback={<div className="loading">Loading page...</div>}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
3 Key Best Practices Checklist
- ✅ Keep components small and focused on a single responsibility.
- ✅ Lift state only as high as necessary.
- ✅ Use unique, stable IDs for
keyprops — never array indices. - ✅ Colocate state with the component that needs it.
- ✅ Avoid creating functions or objects inside JSX return — they create new references every render.
- ✅ Use React DevTools Profiler to identify slow components before optimizing.
- ✅ Apply
React.memoanduseCallbackonly after measuring — premature optimization adds complexity. - ✅ Lazy-load heavy routes and third-party libraries.
4 Code Challenge
Challenge: Take an existing component that renders a list of 500 items and optimize it: lazy-load it with
React.lazy, wrap items in React.memo, and use useCallback for any handlers. Measure before/after using React DevTools Profiler.