{"id":2830,"date":"2022-07-15T09:56:45","date_gmt":"2022-07-15T04:26:45","guid":{"rendered":"http:\/\/uitutorials.in\/wp\/?p=2830"},"modified":"2022-07-15T09:56:45","modified_gmt":"2022-07-15T04:26:45","slug":"reactjs-usememo-and-usecallback-hooks","status":"publish","type":"post","link":"https:\/\/uitutorials.in\/wp\/reactjs-usememo-and-usecallback-hooks\/","title":{"rendered":"Reactjs &#8211; useMemo and useCallback hooks"},"content":{"rendered":"<p>Think of memoization as caching a value so that it does not need to be recalculated.<\/p>\n<h2>useMemo<\/h2>\n<p>The React useMemo Hook returns a memoized value.<\/p>\n<p>The useMemo Hook only runs when one of its dependencies update.This can improve performance.<\/p>\n<p>The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function. <\/p>\n<p>To fix this performance issue, we can use the useMemo Hook to memoize the expensiveCalculation function. This will cause the function to only run when needed.<\/p>\n<p>We can wrap the expensive function call with useMemo.<\/p>\n<p>The useMemoHook accepts a second parameter to declare dependencies. The expensive function will only run when its dependencies have changed.<\/p>\n<p>In the following example, the expensive function will only run when count is changed and not when todo&#8217;s are added.<\/p>\n<p>index.js<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">import { useState, useMemo } from \"react\";\r\nimport ReactDOM from \"react-dom\/client\";\r\n\r\nconst App = () =&gt; {\r\n  const [count, setCount] = useState(0);\r\n  const [todos, setTodos] = useState([]);\r\n  const calculation = useMemo(() =&gt; expensiveCalculation(count), [count]);\r\n\r\n  const increment = () =&gt; {\r\n    setCount((c) =&gt; c + 1);\r\n  };\r\n  const addTodo = () =&gt; {\r\n    setTodos((t) =&gt; [...t, \"New Todo\"]);\r\n  };\r\n\r\n  return (\r\n    &lt;div&gt;\r\n      &lt;div&gt;\r\n        &lt;h2&gt;My Todos&lt;\/h2&gt;\r\n        {todos.map((todo, index) =&gt; {\r\n          return &lt;p key={index}&gt;{todo}&lt;\/p&gt;;\r\n        })}\r\n        &lt;button onClick={addTodo}&gt;Add Todo&lt;\/button&gt;\r\n      &lt;\/div&gt;\r\n      &lt;hr \/&gt;\r\n      &lt;div&gt;\r\n        Count: {count}\r\n        &lt;button onClick={increment}&gt;+&lt;\/button&gt;\r\n        &lt;h2&gt;Expensive Calculation&lt;\/h2&gt;\r\n        {calculation}\r\n      &lt;\/div&gt;\r\n    &lt;\/div&gt;\r\n  );\r\n};\r\n\r\nconst expensiveCalculation = (num) =&gt; {\r\n  console.log(\"Calculating...\");\r\n  for (let i = 0; i &lt; 1000000000; i++) {\r\n    num += 1;\r\n  }\r\n  return num;\r\n};\r\n\r\nconst root = ReactDOM.createRoot(document.getElementById('root'));\r\nroot.render(&lt;App \/&gt;);\r\n\r\n<\/code><\/pre>\n<h2>useCallback<\/h2>\n<p>The React useCallback Hook returns a memoized callback function.<\/p>\n<p>This allows us to isolate resource intensive functions so that they will not automatically run on every render.<\/p>\n<p>The useCallback Hook only runs when one of its dependencies update.This can improve performance.<\/p>\n<p><strong>Problem<\/strong> : One reason to use useCallback is to prevent a component from re-rendering unless its props have changed.<\/p>\n<p><strong>Solution : <\/strong>To fix this, we can use the useCallback hook to prevent the function from being recreated unless necessary.<\/p>\n<p>Use the useCallback Hook to prevent the Todos component from re-rendering needlessly:<br \/>\nindex.js<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">import { useState, useCallback } from \"react\";\r\nimport ReactDOM from \"react-dom\/client\";\r\nimport Todos from \".\/Todos\";\r\n\r\nconst App = () =&gt; {\r\n  const [count, setCount] = useState(0);\r\n  const [todos, setTodos] = useState([]);\r\n\r\n  const increment = () =&gt; {\r\n    setCount((c) =&gt; c + 1);\r\n  };\r\n  const addTodo = useCallback(() =&gt; {\r\n    setTodos((t) =&gt; [...t, \"New Todo\"]);\r\n  }, [todos]);\r\n\r\n  return (\r\n    &lt;&gt;\r\n      &lt;Todos todos={todos} addTodo={addTodo} \/&gt;\r\n      &lt;hr \/&gt;\r\n      &lt;div&gt;\r\n        Count: {count}\r\n        &lt;button onClick={increment}&gt;+&lt;\/button&gt;\r\n      &lt;\/div&gt;\r\n    &lt;\/&gt;\r\n  );\r\n};\r\n\r\nconst root = ReactDOM.createRoot(document.getElementById('root'));\r\nroot.render(&lt;App \/&gt;);<\/code><\/pre>\n<p>Todos.js<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">import { memo } from \"react\";\r\n\r\nconst Todos = ({ todos, addTodo }) =&gt; {\r\n  console.log(\"child render\");\r\n  return (\r\n    &lt;&gt;\r\n      &lt;h2&gt;My Todos&lt;\/h2&gt;\r\n      {todos.map((todo, index) =&gt; {\r\n        return &lt;p key={index}&gt;{todo}&lt;\/p&gt;;\r\n      })}\r\n      &lt;button onClick={addTodo}&gt;Add Todo&lt;\/button&gt;\r\n    &lt;\/&gt;\r\n  );\r\n};\r\n\r\nexport default memo(Todos);<\/code><\/pre>\n<p>Now the Todos component will only re-render when the todos prop changes.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Think of memoization as caching a value so that it does not need to be recalculated. useMemo The React useMemo Hook returns a memoized value. The useMemo Hook only runs when one of its dependencies update.This can improve performance. The useMemo and useCallback Hooks are similar. The main difference is<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[106],"tags":[107],"class_list":["post-2830","post","type-post","status-publish","format-standard","hentry","category-react","tag-react","ct-col-2"],"_links":{"self":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/2830","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/comments?post=2830"}],"version-history":[{"count":1,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/2830\/revisions"}],"predecessor-version":[{"id":2831,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/2830\/revisions\/2831"}],"wp:attachment":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/media?parent=2830"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/categories?post=2830"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/tags?post=2830"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}