M
M
miliko mikoyan2019-07-06 04:37:22
React
miliko mikoyan, 2019-07-06 04:37:22

When to use useCallback, useMemo and useEffect?

What is the main difference between useCallback, useMemo and useEffect. Give examples of using useCallback, useMemo and useEffect.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LEXA_JA, 2019-07-06
@miliko0022

useEffect is a hook that allows you to use a side effect. In classes, its counterpart was the use of componentDidMount, componentDidUpdate and componentWillUnmount. You can make subscriptions, send requests to manage animations, etc.

const [data, setData] = useState(null);

useEffect(() => {
  const controller = new AbortController()
  fetchData(controller.signal).then(setData)

  return () => controller.abort()
}, [fetchData, setData])

useCallback and useMemo are for optimization purposes. useCallback takes a function and an array of arguments, and returns the same function, as long as the arguments haven't changed. useMemo differs in that it does not return the function itself, but the result of its execution. For the most part, they are interchangeable.
Thus, useMemo is used to store the results of heavy calculations, such as array processing.
const data = useMemo(() => array.map(mapper).filter(predicate).reduce(reducer), [array])

And useCallback is used when the persistence of function references is important. For example, when we pass a reference to a component that uses React.PureComponent or React.memo, or when a function is used as an argument in other hooks
const handler = useCallback(() => {
  // что-то сделать 
}, [])

useEffect(() => {
  handler(value)
  // если не использовать useCallback, эффект будет срабатывать постоянно 
}, [handler, value])

D
dmitryvakarev, 2020-03-08
@dmitryvakarev

It is better to carefully study the doc, it is translated into Russian, otherwise you can miss the point
https://ru.reactjs.org/docs/hooks-effect.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question