diff --git a/content/react/concepts/hooks/terms/useMemo/useMemo.md b/content/react/concepts/hooks/terms/useMemo/useMemo.md new file mode 100644 index 00000000000..29642912a79 --- /dev/null +++ b/content/react/concepts/hooks/terms/useMemo/useMemo.md @@ -0,0 +1,72 @@ +--- +Title: 'useMemo()' +Description: 'Returns a memoized value that only recalculates when one of its dependencies changes, helping to avoid expensive calculations on every render.' +Subjects: + - 'Computer Science' + - 'Web Development' +Tags: + - 'Components' + - 'React' +CatalogContent: + - 'react-101' + - 'paths/front-end-engineer-career-path' +--- + +The **`useMemo()`** hook memoizes the result of a computation and recomputes it only when one of its dependencies changes. It is primarily used to optimize performance by avoiding unnecessary recalculations during re-renders. + +When a [component](https://www.codecademy.com/resources/docs/react/components) re-renders, all the code inside it runs again. If there is a slow or heavy calculation, it will run every time — even if the inputs have not changed. The `useMemo()` hook solves this by remembering (or "memoizing") the result and only recalculating when needed. + +## Syntax + +```pseudo +import { useMemo } from 'react'; + +const memoizedValue = useMemo(() => { + return computedResult; +}, [dependency1, dependency2]); +``` + +- The first argument is a [function](https://www.codecademy.com/resources/docs/javascript/functions) that returns the value to be memoized. +- The second argument is an [array](https://www.codecademy.com/resources/docs/javascript/arrays) of dependencies. React performs a shallow comparison of these values and only recomputes when one changes. +- If the dependency array is empty (`[]`), the value is calculated only once when the component first mounts. + +> **Note:** `useMemo()` is meant for performance optimization. The code should still work correctly without it — it should not be used to control when code runs. + +## Example + +In this example, a list of numbers is filtered based on a threshold value. The filtering only runs again when the `numbers` array or the `threshold` value changes, not on every render: + +```jsx +import React, { useState, useMemo } from 'react'; + +function FilteredList() { + const [threshold, setThreshold] = useState(5); + const [count, setCount] = useState(0); + + const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + + const filteredNumbers = useMemo(() => { + console.log('Filtering numbers...'); + return numbers.filter((num) => num >= threshold); + }, [threshold]); + + return ( +