Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question