Skip to content

Instantly share code, notes, and snippets.

@arnoldc
Last active August 8, 2023 14:22
Show Gist options
  • Save arnoldc/ed3781cb1f08e72e1e978a8da8ae3b04 to your computer and use it in GitHub Desktop.
Save arnoldc/ed3781cb1f08e72e1e978a8da8ae3b04 to your computer and use it in GitHub Desktop.
[React] useMemo memo
// memo in react is just render if props have changed, its not the traditional memoization
// use only when computation is expensive
// ************** Good ****************
const value = useMemo(() => numbers.reduce((a, b) => a + b, 0), [numbers]);
// ^ this is ok , because we are using useMemo to calculate a value based on an array of numbers
const multipliedValues = useMemo(() => numbers.map(n => n * 2), [numbers])
// ^ this is ok , because we are using useMemo to calculate a value based on an array of numbers
const person = useMemo(() => ({
first,
last,
full: `${first} ${last}`,
}), [first, last])
// ^ this is ok, because we are using useMemo to calculate a value based on two strings
const sortedPeople = useMemo(() => [...people].sort(), [people])
// ^ this is ok, because this is a heavy operation
const sortedNames = useMemoe(() => sortedPeople.map(p => p.full), [sortedPeople, sortFunc])
const sortFunc = useCallback((a, b) => a.last.localeCompare(b.last), []);
<NameList names={sortedNames} sortFunc={sortFunc} />
// ^ sortedNames and sortFunc are not recreated on every render , this is with the help of useMemo and useCallback
// ************** Bad ****************
const value = useMemo(() => number1 + number2 , [number1, number2])
// value variable is a primitive value, so it's not necessary to use useMemo
const value = useMemo(() => ({ first, last }), [first, last])
// value variable is an object, so it's not necessary to use useMemo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment