15
182

What are the differences in useEffect, useMemo and useCallback

Reading Time: 2 minutes

useEffect, useMemo and useCallback are quite confusing sometime for someone who is new to react. Thus, we will go though the differences in a a bit of details here.

For individual description of each hooks, more references are in these useEffect, useMemo and useCallback articles.

What are the differences

Let’s summarise them into shorter version. We will go into the details illustration later on.

  • useEffect: Execute callback function after every render as long as there is an update to the dependencies.
  • useMemo: Return the cached return value if dependencies don’t change.
  • useCallback: Return the cached function unexecuted if dependencies don’t change.

Explanation Details

useEffect

In useEffect hook, the callback function will execute whenever the dependencies changes.

import { useEffect } from 'react';

const someComponent = (props) => {

  useEffect(() => {
    console.log(props.name);
  },[props.name]);
};

useMemo

In useMemo hook, the callback function will execute whenever the dependencies changes and will return the new value.

If there is no change in the dependencies, it will return the cached value and will skip executing whatever that is inside the callback function.

const [ displayValue, setDisplayValue ] = useState(100);

const displayValueNicely = useMemo(
  () => veryLongProcessMethod(displayValue),
  [displayValue]
);

useCallback

When using useCallback hook, the callback function will contain the action function to be memorised. This actual function will only change if the dependency changes.

This is different from useMemo where the callback function is the calling function itself.

Hence, if we use useCallback hook in the below scenario, the button will not re-render itself unless displayValue changes.

const [ displayValue, setDisplayValue ] = useState(100);

const displayValueNicely = useCallback(
  (fruitCount) => {veryLongProcessMethod(displayValue, displayValue)},
  [displayValue]
);

return (
<button type='button' onClick={() => setDisplayValue(1)}>
);

Conclusion

While useEffect hook’s main purpose is to provide the functionality to perform operation after rendering, useMemo and useCallback adds a later to improve the performance by reducing the need to re-execute function or re-rendering of component.

Although useMemo and useCallback hook may seems to be an upgraded version, there is always another side to considering if the comparison processing time will offset the benefits these hooks provide or not.

Show Comments

No Responses Yet

Leave a Reply