Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React hooks: passing a Functional component as a callback to Array.prototype.map #763

Closed
tearingItUp786 opened this issue Dec 7, 2019 · 2 comments

Comments

@tearingItUp786
Copy link

@tearingItUp786 tearingItUp786 commented Dec 7, 2019

Howdy Kent

I ran into an issue where if I provided a function that used hooks in its implementation and returned some JSX to the callback for Array.prototype.map. The error I received was React Error: Rendered fewer hooks than expected. This article gave me the solution I was looking for but not a very detailed explanation

Here's an example of what I'm talking about although this probably won't break; I just wanted to clarify for you.

  function Foo({ val, key }) {
    const [cool, updateCool] = React.useState(false);

    return <button key={ key } onClick={ () => updateCool(!cool) }>{ val }</button>
  }

  function App() {
    const values = [ {val: 1, key: 1}, { val: 2, key: 2 }, { val: 3, key: 3 }]

  return (<div>
      { values.map(Foo) } {/* broken */}
      { values.map(obj => <Foo {...obj} />) } {/* works */}
    </div>)
  }
@tearingItUp786

This comment has been minimized.

Copy link
Author

@tearingItUp786 tearingItUp786 commented Dec 14, 2019

For those of y'all interested in the answer, check out @kentcdodds blog post here: https://kentcdodds.com/blog/dont-call-a-react-function-component

@kentcdodds

This comment has been minimized.

Copy link
Owner

@kentcdodds kentcdodds commented Dec 14, 2019

Thanks @tearingItUp786! I forgot to come back here to provide the link myself 😅

I hope it was helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.