{"id":27434,"date":"2022-12-15T13:42:10","date_gmt":"2022-12-15T21:42:10","guid":{"rendered":"https:\/\/coderpad.io\/?p=27434"},"modified":"2023-06-05T13:47:10","modified_gmt":"2023-06-05T20:47:10","slug":"a-guide-to-using-reacts-usememo-hook","status":"publish","type":"post","link":"https:\/\/coderpad.io\/blog\/development\/a-guide-to-using-reacts-usememo-hook\/","title":{"rendered":"A Guide To Using React&#8217;s useMemo Hook"},"content":{"rendered":"\n<p>React is one of the most used JavaScript libraries, and it is used for building fast and interactive user interfaces. But at times, implementing certain functions, fetching massive data from external sources, and lots more make it difficult for your React applications to run fast, thereby reducing performance.<\/p>\n\n\n\n<p>In this guide, you will learn what the <code>useMemo<\/code> hook means, how you can use it to optimize your React applications, and when you should use it. You will also get to know other options you can use in other situations, so you don&#8217;t use the <code>useMemo<\/code> hook when you should not.<\/p>\n\n\n\n<p>The <code>useMemo<\/code> hook memoizes values in your React application. These values usually come from expensive functions, and you use the <code>useMemo<\/code> hook to store the value, so the expensive function doesn&#8217;t always run.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\">\n<p>\ud83d\udca1 Expensive functions are those that require a significant amount of time and resources (memory or processing power) to execute.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">What is memoization?<\/h2>\n\n\n\n<p>Memorization is a powerful optimization technique that caches computation results to retrieve them from the cache when needed. Hence, this speeds up your code because you don&#8217;t need to repeat unnecessary computations of expensive functions.<\/p>\n\n\n\n<p>An excellent example is the Fibonacci sequence. Each number in the Fibonacci sequence, or &#8220;Fibonacci number,&#8221; is the sum of the two numbers in the sequence before it. This sequence starts with 0 and 1. The third number is the addition of the first two in the sequence, which are 0 and 1, to become 1, and so on, as seen below:<\/p>\n\n\n\n<p><code><em>0, 1, 1, 2, 3, 5, 8, 13, 21, 34<\/em>, ...<\/code><\/p>\n\n\n\n<p>If you are to write a program to solve this, you can use recursion because each element is the sum of the previous two elements:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> fibonacci = <span class=\"hljs-function\">(<span class=\"hljs-params\">n<\/span>) =&gt;<\/span> {\n    <span class=\"hljs-keyword\">if<\/span> (n &lt;= <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> fibonacci(n - <span class=\"hljs-number\">1<\/span>) + fibonacci(n - <span class=\"hljs-number\">2<\/span>)\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The above uses recursion; meaning it will continue to call a copy of itself until its value is less than one, then it returns one. To understand this better, here is an illustration of how this will work if you want to calculate for <code>fibonacci(5)<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6b77294b7.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">A visual tree with branches displaying the Fibonacci sequence from 0 to 5. The tree is used to visually represent the fibonacci sequence and its progression.<\/figcaption><\/figure>\n\n\n\n<p>In the above, you will notice that <code>fibonacci(3)<\/code>, <code>fibonacci(2)<\/code>, <code>fibonacci(1)<\/code>, and <code>fibonacci(0)<\/code> are calculated several times, which can affect the speed when you have to do more expensive calculations or if you want to get the 35th value.&nbsp;<\/p>\n\n\n\n<p>You can fix this by introducing memorization, which lets you store the values of these positions and only return them instead of having to recompute them several times:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> fibonacci = <span class=\"hljs-function\">(<span class=\"hljs-params\">n, memoValues<\/span>) =&gt;<\/span> {\n    memoValues = memoValues || {}\n\n    <span class=\"hljs-keyword\">if<\/span> (memoValues&#91;n]) <span class=\"hljs-keyword\">return<\/span> memoValues&#91;n]\n\n    <span class=\"hljs-keyword\">if<\/span> (n &lt;= <span class=\"hljs-number\">1<\/span>) <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-number\">1<\/span>\n    <span class=\"hljs-keyword\">return<\/span> memoValues&#91;n] = fibonacci(n<span class=\"hljs-number\">-1<\/span>, memoValues) + fibonacci(n<span class=\"hljs-number\">-2<\/span>, memoValues)\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The code above checks if there is a cached value; if so, it prevents recursion. If there is no cached value, it calculates the recursion and saves it to the cache immediately before returning the value. To understand this better, here is what the illustration for <code>fibonacci(5)<\/code> now looks like:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6b78e7fa9.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">A visual tree displaying the Fibonacci sequence from 0 to 5, but with memoization applied to improve calculation performance and efficiency.<\/figcaption><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote\">\n<p>\ud83d\udca1 Cache is a type of temporary storage that a computer or program uses to hold data that is likely to be accessed again in the near future.&nbsp;&nbsp;<\/p>\n<\/blockquote>\n\n\n\n<p>There is no repetition, and the functions with blue backgrounds are getting &#8220;memoized values&#8221; instead of recomputing them.<\/p>\n\n\n\n<p>Now that we have a basic understanding of memoization, let&#8217;s see how it can help you store the values of expensive computations in your React application for better performance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">React re-rendering problem<\/h2>\n\n\n\n<p>In React, whenever a state or prop updates or value changes, the component(s) re-renders, meaning all expensive functions, computations, and API requests are re-rendered, leading to slow performance. It doesn&#8217;t matter if the state has nothing to do with the other components; when a state changes in the parent component, every other component will re-render.<\/p>\n\n\n\n<p>To explain this, let&#8217;s create a react application that involves expensive calculations like the factorial calculation:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">import<\/span> { useState } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'react'<\/span>;\n<span class=\"hljs-keyword\">import<\/span> <span class=\"hljs-string\">'.\/App.css'<\/span>;\n\n<span class=\"hljs-keyword\">const<\/span> calculateFibonacci = <span class=\"hljs-function\">(<span class=\"hljs-params\">n<\/span>) =&gt;<\/span> {\n    <span class=\"hljs-keyword\">if<\/span> (n &lt; <span class=\"hljs-number\">2<\/span>) {\n        <span class=\"hljs-keyword\">return<\/span> n;\n    }\n    <span class=\"hljs-keyword\">return<\/span> calculateFibonacci(n - <span class=\"hljs-number\">1<\/span>) + calculateFibonacci(n - <span class=\"hljs-number\">2<\/span>);\n};\n\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">const<\/span> App = <span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n    <span class=\"hljs-keyword\">const<\/span> &#91;number, setNumber] = useState(<span class=\"hljs-number\">0<\/span>);\n    <span class=\"hljs-keyword\">const<\/span> &#91;name, setName] = useState(<span class=\"hljs-string\">''<\/span>);\n    <span class=\"hljs-keyword\">const<\/span> fibonacciResult = calculateFibonacci(number);\n\n    <span class=\"hljs-keyword\">return<\/span> (\n        <span class=\"xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"container\"<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">h1<\/span>&gt;<\/span>Fibonacci Calculator<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">h1<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">input<\/span>\n                <span class=\"hljs-attr\">type<\/span>= <span class=\"hljs-string\">\"number\"<\/span>\n                <span class=\"hljs-attr\">value<\/span>=<span class=\"hljs-string\">{number}<\/span>\n                <span class=\"hljs-attr\">onChange<\/span>=<span class=\"hljs-string\">{(e)<\/span> =&gt;<\/span> setNumber(e.target.value)}\n            \/&gt;\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">p<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"bold\"<\/span>&gt;<\/span>\n                This Fibonacci result for <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">span<\/span>&gt;<\/span>{number}<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">span<\/span>&gt;<\/span> is{' '}\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">span<\/span>&gt;<\/span>{fibonacciResult}<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">span<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">p<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"container2\"<\/span>&gt;<\/span>\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">label<\/span>&gt;<\/span>Please Enter your name to see that it is slow:<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">label<\/span>&gt;<\/span>\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">input<\/span>\n                    <span class=\"hljs-attr\">type<\/span>= <span class=\"hljs-string\">\"text\"<\/span>\n                    <span class=\"hljs-attr\">value<\/span>=<span class=\"hljs-string\">{name}<\/span>\n                    <span class=\"hljs-attr\">onChange<\/span>=<span class=\"hljs-string\">{(e)<\/span> =&gt;<\/span> setName(e.target.value)}\n                \/&gt;\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">p<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"bold\"<\/span>&gt;<\/span>{name || 'The name will appear here...'}<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">p<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span><\/span>\n    );\n};<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In the application above, there are two states, one to store the number from the input form while the second to store the name. Basically, what this application does is that any number you input into the number field will calculate the factorial using the external function placed outside the component:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> calculateFibonacci = <span class=\"hljs-function\">(<span class=\"hljs-params\">n<\/span>) =&gt;<\/span> {\n    <span class=\"hljs-keyword\">if<\/span> (n &lt; <span class=\"hljs-number\">2<\/span>) {\n        <span class=\"hljs-keyword\">return<\/span> n;\n    }\n    <span class=\"hljs-keyword\">return<\/span> calculateFibonacci(n - <span class=\"hljs-number\">1<\/span>) + calculateFibonacci(n - <span class=\"hljs-number\">2<\/span>);\n};<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This expensive function is called inside the component, and the number state is passed into it, so it calculates the value, and you can then display it in the application:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> fibonacciResult = calculateFibonacci(number);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>But the problem here is that whenever a state is updated, this function will always run even when the state does not affect the number state. For example, there is a <code>name<\/code> state; whenever you type into the name input field, it will always re-render the component, thereby always running this expensive function.<\/p>\n\n\n\n<p>Let&#8217;s test this. If you pass a number from <code>35<\/code> upwards, you will begin to notice that it takes some seconds to calculate. This is because it will need to do a lot of recursions, as you can see in the GIF below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6b7a238c5.gif\" alt=\"\"\/><\/figure>\n\n\n\n<p>That is not the problem, but the problem is that when you try to do anything on your application that involves a state, it will take time because the application will re-render. Meaning the Fibonacci function will always calculate the value for the number passed.&nbsp;<\/p>\n\n\n\n<p>As you see below, when I type the name, even though it shows the component re-renders, it takes time for the name to appear because the function is calculated for each render.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6b7f65078.gif\" alt=\"\"\/><\/figure>\n\n\n\n<p>To fix this, you will introduce the <code>useMemo<\/code> hook to store the value of <strong><em>expensive<\/em><\/strong> calculations and operations and stop them from continually rendering even when the component re-renders. <code>useMemo<\/code> is an official hook you can import from <code>react<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">import<\/span> { useState, useMemo } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'react'<\/span>;\n\n<span class=\"hljs-comment\">\/\/ ...<\/span>\n\n<span class=\"hljs-keyword\">const<\/span> fibonacciResult = useMemo(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> calculateFibonacci(number), &#91;number]);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>At this point, when you update other states or props in your component, as long as the <code>number<\/code> state does not change, the value will be stored. The expensive function will not compute, making the performance of your application fast:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6b92b7482.gif\" alt=\"\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding the useMemo hook<\/h2>\n\n\n\n<p>The <code>useMemo<\/code> hook is one of the many built-in react hooks that allow you to memoize values in React applications. It is used basically in two situations which are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When computing expensive operations<\/li>\n\n\n\n<li>For referential equality<\/li>\n<\/ul>\n\n\n\n<p>Overall, it memoizes computed values in a React component so that those values will not be recomputed when the component re-renders. This is the general syntax of the <code>useMemo<\/code> hook:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> memoizedValue = useMemo(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n    <span class=\"hljs-keyword\">return<\/span> somevalue\n}, &#91;...dependencies])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>useMemo<\/code> hook receives two arguments and is very similar to the `<a href=\"https:\/\/coderpad.io\/blog\/development\/rules-of-reacts-useeffect\/\">useEffect<\/a>` hook. The first argument is a callback function, which returns the value, and the second is an array of dependencies. When any of the values of any dependencies changes, a re-computation happens, and then the value is memoized again, which triggers the expensive operation. Just as you have seen in the previous example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> fibonacciResult = useMemo(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n\u00a0 \u00a0 <span class=\"hljs-keyword\">return<\/span> calculateFibonacci(number);\n}, &#91;number]);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Referential equality<\/h3>\n\n\n\n<p>In JavaScript, we have primitive and non-primitive data types. When you make an equality on primitive data types, they are checked based on their values, while for non-primitive data types like object and array, equality is based on references.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-comment\">\/\/ primitive<\/span>\n<span class=\"hljs-keyword\">let<\/span> a = <span class=\"hljs-number\">5<\/span>;\n<span class=\"hljs-keyword\">let<\/span> b = <span class=\"hljs-number\">5<\/span>;\n\n<span class=\"hljs-built_in\">console<\/span>.log(a === b); <span class=\"hljs-comment\">\/\/ true<\/span>\n\n<span class=\"hljs-comment\">\/\/ non-primitive<\/span>\n<span class=\"hljs-keyword\">let<\/span> a = {<span class=\"hljs-attr\">name<\/span>: <span class=\"hljs-string\">\"John Doe\"<\/span>};\n<span class=\"hljs-keyword\">let<\/span> b = {<span class=\"hljs-attr\">name<\/span>: <span class=\"hljs-string\">\"John Doe\"<\/span>};\n\n<span class=\"hljs-built_in\">console<\/span>.log(a === b); <span class=\"hljs-comment\">\/\/ false<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Arrays and objects will always return false even though they are equal because their equality is based on references, meaning:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">let<\/span> a = {<span class=\"hljs-attr\">name<\/span>: <span class=\"hljs-string\">\"John Doe\"<\/span>};\n<span class=\"hljs-keyword\">let<\/span> b = {<span class=\"hljs-attr\">name<\/span>: <span class=\"hljs-string\">\"John Doe\"<\/span>};\n\n<span class=\"hljs-built_in\">console<\/span>.log(a.name === b.name); <span class=\"hljs-comment\">\/\/ true<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When objects or functions are declared within your component, they will always be redeclared whenever your component re-renders. Let&#8217;s confirm this in this example.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">import<\/span> { useState, useEffect } <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">'react'<\/span>;\n<span class=\"hljs-keyword\">import<\/span> <span class=\"hljs-string\">'.\/App.css'<\/span>;\n\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">const<\/span> App = <span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n    <span class=\"hljs-keyword\">const<\/span> &#91;name, setName] = useState(<span class=\"hljs-string\">''<\/span>);\n    <span class=\"hljs-keyword\">const<\/span> &#91;darkTheme, setDarkTheme] = useState(<span class=\"hljs-literal\">false<\/span>);\n\n    <span class=\"hljs-keyword\">const<\/span> themeStyles = {\n        <span class=\"hljs-attr\">backgroundColor<\/span>: darkTheme ? <span class=\"hljs-string\">'#333'<\/span> : <span class=\"hljs-string\">'#FFF'<\/span>,\n        <span class=\"hljs-attr\">color<\/span>: darkTheme ? <span class=\"hljs-string\">'#FFF'<\/span> : <span class=\"hljs-string\">'#333'<\/span>,\n    };\n\n    useEffect(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n        <span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-string\">'Theme changed'<\/span>);\n    }, &#91;themeStyles]);\n\n    <span class=\"hljs-keyword\">return<\/span> (\n        <span class=\"xml\"><span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"container\"<\/span> <span class=\"hljs-attr\">style<\/span>=<span class=\"hljs-string\">{themeStyles}<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"container2\"<\/span>&gt;<\/span>\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">label<\/span>&gt;<\/span>Please Enter your name to see that it is slow:<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">label<\/span>&gt;<\/span>\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">input<\/span>\n                    <span class=\"hljs-attr\">type<\/span>= <span class=\"hljs-string\">\"text\"<\/span>\n                    <span class=\"hljs-attr\">value<\/span>=<span class=\"hljs-string\">{name}<\/span>\n                    <span class=\"hljs-attr\">onChange<\/span>=<span class=\"hljs-string\">{(e)<\/span> =&gt;<\/span> setName(e.target.value)}\n                \/&gt;\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">p<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"bold\"<\/span>&gt;<\/span>{name || 'The name will appear here...'}<span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">p<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">div<\/span> <span class=\"hljs-attr\">className<\/span>=<span class=\"hljs-string\">\"toggle\"<\/span>&gt;<\/span>\n                <span class=\"hljs-tag\">&lt;<span class=\"hljs-name\">button<\/span> <span class=\"hljs-attr\">onClick<\/span>=<span class=\"hljs-string\">{()<\/span> =&gt;<\/span> setDarkTheme((prevDark) =&gt; !prevDark)}&gt;\n                    Toggle Theme\n                <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">button<\/span>&gt;<\/span>\n            <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span>\n        <span class=\"hljs-tag\">&lt;\/<span class=\"hljs-name\">div<\/span>&gt;<\/span><\/span>\n    );\n};<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Suppose you have an object that contains styles; you want to use these styles to control the dark mode and light mode display of your application:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> themeStyles = {\n    <span class=\"hljs-attr\">backgroundColor<\/span>: darkTheme ? <span class=\"hljs-string\">'#333'<\/span> : <span class=\"hljs-string\">'#FFF'<\/span>,\n    <span class=\"hljs-attr\">color<\/span>: darkTheme ? <span class=\"hljs-string\">'#FFF'<\/span> : <span class=\"hljs-string\">'#333'<\/span>,\n};<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>A <code>darkTheme<\/code> state is created and has a default value of <code>false<\/code>. When the button is clicked, the value changes to <code>true<\/code>, and then the color will change based on the <code>themeStyles<\/code> object. But the issue is that whenever the component re-renders, this object is<strong> redeclared<\/strong>. Let&#8217;s track this by introducing a <code>useEffect<\/code> hook and passing <code>themeStyles<\/code> as its dependency so it logs out a message whenever the <code>themeStyles<\/code> is redeclared:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\">useEffect(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n    <span class=\"hljs-built_in\">console<\/span>.log(<span class=\"hljs-string\">'Theme changed'<\/span>);\n}, &#91;themeStyles]);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Whenever the name state changes, you will notice the object is redeclared:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/12\/img_639b6ba40eef8.gif\" alt=\"\"\/><\/figure>\n\n\n\n<p>You can fix this with the <code>useMemo<\/code> hook by memoizing the <code>themeStyles<\/code> object so it only redeclares when the <code>darkTheme<\/code> state changes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> themeStyles = useMemo(<span class=\"hljs-function\"><span class=\"hljs-params\">()<\/span> =&gt;<\/span> {\n    <span class=\"hljs-keyword\">return<\/span> {\n        <span class=\"hljs-attr\">backgroundColor<\/span>: darkTheme ? <span class=\"hljs-string\">'#333'<\/span> : <span class=\"hljs-string\">'#FFF'<\/span>,\n        <span class=\"hljs-attr\">color<\/span>: darkTheme ? <span class=\"hljs-string\">'#FFF'<\/span> : <span class=\"hljs-string\">'#333'<\/span>,\n    };\n}, &#91;darkTheme]);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>With this, the <code>useEffect<\/code> hook will only run when the <code>darkTheme<\/code> state changes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">useMemo best practices<\/h2>\n\n\n\n<p>You now know what the <code>useMemo<\/code> hook does and how it helps optimize your React application. This doesn&#8217;t mean you should memoize all values in your React application; instead, you should only memoize values for<strong>expensive functions and referential equality<\/strong>.<\/p>\n\n\n\n<p>The primary goal is to avoid recomputing expensive functions and operations during re-render and resolve reference conflicts between renders It is essential to know that this hook caches these values; thereby, unnecessary memoizing values will lead to using up more memory which can hurt your application.<\/p>\n\n\n\n<p>In React, you can use other hooks and methods to memoize other aspects of your code to ensure optimization. You can use the <a href=\"https:\/\/beta.reactjs.org\/apis\/react\/useCallback\" target=\"_blank\" rel=\"noopener\"><code>useCallback<\/code> hook<\/a> to memoize expensive functions. For example, the <code>calculateFibonacci<\/code> function that was placed outside the component, you can decide to place it within the component but wrap it with the <code>useCallback<\/code> hook:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> calculateFibonacci = useCallback(<span class=\"hljs-function\">(<span class=\"hljs-params\">n<\/span>) =&gt;<\/span> {\n    <span class=\"hljs-keyword\">if<\/span> (n &lt; <span class=\"hljs-number\">2<\/span>) {\n        <span class=\"hljs-keyword\">return<\/span> n;\n    }\n    <span class=\"hljs-keyword\">return<\/span> calculateFibonacci(n - <span class=\"hljs-number\">1<\/span>) + calculateFibonacci(n - <span class=\"hljs-number\">2<\/span>);\n}, &#91;]);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>You can also use <a href=\"https:\/\/beta.reactjs.org\/apis\/react\/useCallback\" target=\"_blank\" rel=\"noopener\">React Memo<\/a> to memoize the rendered output of a component by wrapping around it, thereby avoiding unnecessary renderings.&nbsp;<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript shcb-wrap-lines\"><span class=\"hljs-keyword\">const<\/span> myComponent = React.memo(<span class=\"hljs-function\">(<span class=\"hljs-params\">props<\/span>) =&gt;<\/span> {\n    <span class=\"hljs-comment\">\/* render using props *\/<\/span>\n});\n\n<span class=\"hljs-keyword\">export<\/span> <span class=\"hljs-keyword\">default<\/span> myComponent;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Run the sandbox to view the memoized function in action:<\/p>\n\n\n<div\n\tclass=\"sandbox-embed responsive-embed  sandbox-embed--full-width\"\n\tstyle=\"padding-top: 85%\"\ndata-block-name=\"coderpad-sandbox-embed\">\n\t<iframe src=\"https:\/\/embed.coderpad.io\/sandbox?question_id=237680&#038;use_question_button\" width=\"640\" height=\"544\" loading=\"lazy\" aria-label=\"Try out the CoderPad sandbox\"><\/iframe>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this guide, you have learned what the <code>useMemo<\/code> hook is about, how it works, and when you should use it\u2014knowing when and where you should apply memorization and the specific method to use is essential.<\/p>\n\n\n\n<p>Thanks for reading!<\/p>\n\n\n\n<p><br><em>Hi, I\u2019m Elijah, a technical writer, and software developer, actively sharing all I\u2019ve learned through writing. Follow me on <\/em><a href=\"https:\/\/twitter.com\/asaolu_elijah\" target=\"_blank\" rel=\"noopener\"><em>Twitter<\/em><\/a><em> if you enjoy programming tips and memes.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>React is one of the most used JavaScript libraries, and it is used for building fast and interactive user interfaces. But at times, implementing certain functions, fetching massive data from external sources, and lots more make it difficult for your React applications to run fast, thereby reducing performance. Learn how to optimize your React applications, and when you should use it in this article.<\/p>\n","protected":false},"author":1,"featured_media":27445,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[9],"tags":[],"persona":[29],"blog-programming-language":[61],"keyword-cluster":[],"class_list":["post-27434","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/27434","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/comments?post=27434"}],"version-history":[{"count":92,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/27434\/revisions"}],"predecessor-version":[{"id":32619,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/27434\/revisions\/32619"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media\/27445"}],"wp:attachment":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media?parent=27434"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/categories?post=27434"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/tags?post=27434"},{"taxonomy":"persona","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/persona?post=27434"},{"taxonomy":"blog-programming-language","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/blog-programming-language?post=27434"},{"taxonomy":"keyword-cluster","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/keyword-cluster?post=27434"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}