By Squanchy


2019-07-05 23:10:57 8 Comments

What is the main difference between useCallback,useMemo and useEffect. ?.Give examples of when to use useCallback,useMemo and useEffect.

2 comments

@Vencovsky 2019-07-06 01:49:49

A short explanation.

useEffect

It's the alternative for the class components lifecicle methods (componentDidMount, componentWillUnmount, componentDidUpdate, ... ) and you can also use it as a side effect based on some dependencies, "when some variable change, do this".

useCallback

On every render, everything that is inside the component (function) is runned again, so if some child component have a dependency on some function from the parent component, the child will rerender every time the parent rerender, even if that function "doesn't change" (the reference changes, but what the function will do don't).
It's used for optimization, avoiding this unnecessary child's renders, making the function change the reference only when some dependencies changes. You should use it when a function is a dependency of a side effect e.g. useEffect.

useMemo

It will run on every render, but with cached values. It will only use new values when certain dependencies change. It's used for optimization when you have expensive computation that you. Here is also a good answer that explains it.

@d4vsanchez 2019-07-06 00:42:53

useEffect() will let you create side effects on your components based on the dependencies you send to it.

function Example() {
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'))
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="root"></div>

The example above is taken from the documentation of React. You can see that each time you click the button it will trigger an update on the count field (using setCount()) and then, the effect that depends on the count variable will trigger an update on the title of the page.


useCallback() will return a memoized callback. Normally, if you have a child component that receives a function prop, at each re-render of the parent component, this function will be re-executed; by using useCallback() you ensure that this function is only re-executed when any value on it's dependency array changes.

function ExampleChild({ callbackFunction }) {
  const [value, setValue] = React.useState(0);

  React.useEffect(() => {
    setValue(value + 1)
  }, [callbackFunction]);

  return (<p>Child: {value}</p>);
}

function ExampleParent() {
  const [count, setCount] = React.useState(0);
  const [another, setAnother] = React.useState(0);
  
  const countCallback = React.useCallback(() => {
    return count;
  }, [count]);
  
  return (
    <div>
      <ExampleChild callbackFunction={countCallback} />
      <button onClick={() => setCount(count + 1)}>
        Change callback
      </button>
      
      <button onClick={() => setAnother(another + 1)}>
        Do not change callback
      </button>
    </div>
  )
}

ReactDOM.render(<ExampleParent />, document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="root"></div>


useMemo() will return a memoized value that is the result of the passed parameter. It means that useMemo() will make the calculation for some parameter once and it will then return the same result for the same parameter from a cache.

This is very useful when you need to process a huge amount of data.

function ExampleChild({ value }) {
   const [childValue, setChildValue] = React.useState(0);

   React.useEffect(() => {
     setChildValue(childValue + 1);
   }, [value])

   return <p>Child value: {childValue}</p>;
}

function ExampleParent() {
  const [value, setValue] = React.useState(0);
  const heavyProcessing = () => {
    // Do some heavy processing with the parameter
    console.log(`Cached memo: ${value}`);
    return value;
  };

  const memoizedResult = React.useMemo(heavyProcessing, [value]);
  
  return (
    <div>
      <ExampleChild value={memoizedResult} />
      <button onClick={() => setValue(value + 1)}>
        Change memo
      </button>
    </div>
  )
}

ReactDOM.render(<ExampleParent />, document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="root"></div>

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] React Docs and difference between useMemo and useCallback

6 Answered Questions

[SOLVED] Infinite loop in useEffect

  • 2018-10-30 18:45:54
  • Tobias Haugen
  • 7540 View
  • 28 Score
  • 6 Answer
  • Tags:   reactjs react-hooks

2 Answered Questions

[SOLVED] What does useCallback/useMemo do in React?

2 Answered Questions

[SOLVED] What's the difference between useCallback and useMemo in practice?

  • 2019-03-02 21:34:33
  • java-man-script
  • 3284 View
  • 26 Score
  • 2 Answer
  • Tags:   reactjs

1 Answered Questions

[SOLVED] useMemo vs. useEffect + useState

1 Answered Questions

[SOLVED] useCallback vs. useMemo and when to use them

1 Answered Questions

[SOLVED] When to use useEffect with no deps?

3 Answered Questions

[SOLVED] In React Hook useCallback, How are (a,b) used

  • 2019-03-13 22:56:32
  • Peter Kellner
  • 863 View
  • 1 Score
  • 3 Answer
  • Tags:   reactjs react-hooks

1 Answered Questions

[SOLVED] How to avoid issue with unguaranteed useCallback deps in useEffect deps?

  • 2019-03-29 00:49:13
  • Pandaiolo
  • 308 View
  • 4 Score
  • 1 Answer
  • Tags:   react-hooks

2 Answered Questions

Sponsored Content