title: React custom hooks and useMemo hooks
body: <p>I have two &quot;expensive&quot; functions that I would like to memoize in my react application, as they take a long time to render.  The expensive functions are used in an array map. I would like to memoize each result of the array map, so that if one element of the array is changed, only that element's expensive functions will be recalculated. (And to memoize the expensive functions independently, as sometimes only one will need to be recalculated.)  I'm struggling with how to memoize and pass in the current array value.</p>
  <p>Here is the working demo, without memoization:</p>
  <pre><code>import React, { useMemo, useState } from &quot;react&quot;;
  
  const input = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;durian&quot;, &quot;elderberry&quot;, &quot;apple&quot;];
  
  export default function App() {
    const output = input.map((msg, key) =&gt; createItem(msg, key));
    return &lt;div className=&quot;App&quot;&gt;{output}&lt;/div&gt;;
  }
  
  const createItem = (message, key) =&gt; {   // expensive function 1
    console.log(&quot;in createItem:&quot;, key, message);
  
    return (
      &lt;div key={key}&gt;
        &lt;strong&gt;{&quot;Message &quot; + (1 + key)}: &lt;/strong&gt;
        {message} =&gt;{&quot; &quot;}
        &lt;span
          id={&quot;preview-&quot; + key}
          dangerouslySetInnerHTML={{ __html: msgSub(message) }}
        /&gt;
      &lt;/div&gt;
    );
  };
  
  const msgSub = message =&gt; {   // expensive function 2
    const messageSub = message.replace(/[a]/g, &quot;A&quot;).replace(/[e]/g, &quot;E&quot;);
    console.log(&quot;in msgSub:&quot;, message, messageSub);
    return messageSub;
  };
  </code></pre>
  <p>(I don't have it functioning on SO's editor, so view and run it on <a href="https://codesandbox.io/s/still-glitter-bxy7z?file=/src/App.js:0-826" rel="nofollow noreferrer">codesandbox</a>.)</p>
  <p>Here is <a href="https://codesandbox.io/s/attempt-with-custom-hooks-and-usememo-3duwk?file=/src/App.js" rel="nofollow noreferrer">one of my attempts</a> using custom hooks and useMemo hooks.</p>
  <p>Any guidance would be greatly appreciated!</p>
  <p>And bonus points for illustrating how to get react to work in SO's editor!</p>