title: React hooks useCallback with parameters inside loop
body: <p>I'm trying to learn about the hooks functionality, however I can't quite seem to figure out how I'm supposed to use the function <code>useCallback</code> properly. As far as I understand from the rules about hooks I'm supposed to call them top-level and not within logic (such as loops). Which leads me to be quite confused how I'm supposed to implement <code>useCallback</code> on components that are rendered from a loop.</p>
  
  <p>Take a look at the following example snippet where I create 5 buttons with an <code>onClick</code> handler that prints the number of the button to the console.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const Example = (props) =&gt; {
    const onClick = (key) =&gt; {
      console.log("You clicked: ", key);
    };
    
    return(
      &lt;div&gt;
        {
          _.times(5, (key) =&gt; {
            return (
              &lt;button onClick={() =&gt; onClick(key)}&gt;
                {key}
              &lt;/button&gt;
            );
          })
        }
      &lt;/div&gt;
    );
  };
  console.log("hello there");
  
  ReactDOM.render(&lt;Example/&gt;, document.getElementById('root'));</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"&gt;&lt;/script&gt;
  &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt;
  &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;
  
  &lt;div id='root'&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Right now it creates a new function instance everytime the Example renders due to my use of the arrow function within the <code>&lt;button onClick={() =&gt; onClick(key)}&gt;</code>, which I do because I want the <code>onClick</code> function to know which button called it. I thought I could prevent this with the new react hooks functionality by using <code>useCallback</code>, however if I apply it to the <code>const onClick</code> then it would still create a new instance every render because of the inline arrow function needed to give the <code>key</code> parameter, and I'm not allowed to apply it to the render within a loop as far as I know (especially if the loop order might change right?).</p>
  
  <p>So how would I go about implementing <code>useCallback</code> in this scenario while keeping the same functionality? Is it at all possible?</p>