Last active
January 2, 2026 18:14
-
-
Save Abdulrezak-halid/74fbb892d8580bc1d8b4bfba28fd6c8c to your computer and use it in GitHub Desktop.
React Performance - useMemo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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