D
D
Dosya2021-09-24 08:14:08
React
Dosya, 2021-09-24 08:14:08

What is the difference between useMemo hook and useCallback hook in React?

Hello everyone, I am a newbie. I am currently learning the React js framework. I started to understand hooks like useState, useEffect, but I can't figure out the difference between useMemo and useCallback hooks. And why are they needed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2021-09-24
@Dasihub

There are two
differences 1) useCallback(func, deps) - nothing more than useMemo(() => func, deps)
That is, useCallback returns a function, and useMemo executes a function and returns a result (in both cases, provided that the deps have changed).
2) about useMemo in the documentation there is a warning that React does not guarantee the safety of the result and can calculate again, even with unchanged deps. This is not said about useCallback.

J
JS Noob, 2021-09-24
@JS_Noob

Both hooks are needed so that when passing the data they return as props to a child component, this child component does not perform unnecessary re-renders.
That is, the useCallback hook, with the same dependencies, will create a link to the function once. When passed to a child component, this child component will check that the reference has not changed and will not do an extra rerender.
The useMemo hook is needed for the same, but if useCallback returns a function, then useMemo returns some data. And as mentioned earlier, useMemo does not guarantee that the data reference will not change even with the same dependencies.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question