Skillversitas

Optimizing Performance

React.memo

Prevents re-renders if the props do not change.

import { memo } from 'react';
const UserCard = memo(function UserCard({ name, email }) {
  return <div><h3>{name}</h3><p>{email}</p></div>;
});

useMemo & useCallback

Cache computations and functions so their references stay stable.

import { useMemo, useCallback } from 'react';

function List({ items, query }) {
  const filtered = useMemo(
    () => items.filter(i => i.name.includes(query)), [items, query]
  );
  const handleClick = useCallback(() => {}, []);
  return <ul>{filtered.map(i => <li key={i.id}>{i.name}</li>)}</ul>;
}

Lazy Loading

import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Dashboard />
    </Suspense>
  );
}

Virtual Lists

For thousands of items, use react-window:

import { FixedSizeList } from 'react-window';
function VList({ items }) {
  return (
    <FixedSizeList height={400} itemCount={items.length} itemSize={35}>
      {({ index, style }) => <div style={style}>{items[index].name}</div>}
    </FixedSizeList>
  );
}

Avoid Inline Objects/Functions

// Wrong
<Comp style={{ color: 'red' }} onClick={() => doSomething()} />
// Correct
const style = { color: 'red' };
<Comp style={style} onClick={handleClick} />

Measure before you optimize. Next chapter: Testing React.