Skip to content

Instantly share code, notes, and snippets.

@Abdulrezak-halid
Last active January 2, 2026 18:14
Show Gist options
  • Select an option

  • Save Abdulrezak-halid/74fbb892d8580bc1d8b4bfba28fd6c8c to your computer and use it in GitHub Desktop.

Select an option

Save Abdulrezak-halid/74fbb892d8580bc1d8b4bfba28fd6c8c to your computer and use it in GitHub Desktop.
React Performance - useMemo
import { useMemo } from "react";
/**
* useMemo – When and Why to Use It
*
* ✅ Use useMemo when:
* - You have an expensive calculation (loops, reduce, filter on large arrays)
* - The result is derived from props or state
* - The calculation should not re-run on every re-render
*
* ❌ Do NOT use useMemo when:
* - The calculation is cheap
* - The dependency changes every render
* - You use it everywhere without measuring performance
*/
type IItem = {
id: number;
price: number;
};
type IProps = {
items: IItem[];
};
export function TotalPrice({ items }: IProps) {
const total = useMemo(() => {
console.log("Calculating total...");
return items.reduce((sum, item) => sum + item.price, 0);
}, [items]);
return <div>Total: {total}</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment