When you use parent-child nesting, the parent component calls setState and the state changes and the child component will execute the function unconditionally if there is a send request in the function, it will cause a lot of performance waste, so the function that will be called is wrapped in useMemo, The second argument is important and the function is executed again only if the argument changes

The application of useMemo

UseMemo is similar to useCallback in that useCallback can also cache optimizations for incoming child components.

The first argument to useMemo takes a function and the second argument is an array

Const xiaohong = fn () changed to

Const xiaohong = useMemo (() => fn (), [count])

You can put some expensive computational logic into useMemo and update it only when the dependency value changes. const num = useMemo(() => { let num = 0; // Here we use count to do some very complicated calculations for num. When count does not change, component rerendering returns the cached value directly. return num; }, [count]);

return

{num}

conclusion

UseCallback and useMemo: one caches functions, and the other caches the return results of functions. UseCallback is used to optimize subcomponents to prevent repeated rendering of subcomponents. UseMemo can optimize the current component as well as its subcomponents by memoize some of the more complex computational logic. Use useMemo in order to check the inputs for simple calculations: use useMemo in order to check the inputs for simple calculations: 😅