How to fix React Error: Rendered fewer hooks than expected

Photo by FuYong Hua on Unsplash

TLDR;

  • Only call hooks from the top level of a component, and never put them in conditional statements.
  • Make sure you only call hooks from within a React Component.
  • Further, pass the component around using Component syntax <MyComponent /> instead of calling the function component directly myComponent() !
export default function ListView({history, match}) {
const filter = match.params.filter
let [items, maxPages] = useTopStories(filter, page)
// don't use hooks within a conditional statement!
if (filter === 'jobs') {
const [jobs, setJobs] = useState([])
}


//...
}

The Problem

export default function Comment({id}) {
const { by, time, text, kids = [] } = useItemSubscription(id)
const [showComments, setShowComments] = useState(true)

return (
<div key={id}>
<div className="text">
{ text && text }
</div>
{
kids.length ? kids.map(id => Comment({id})) : null
}
</div>
)
}

Solution

export default function Comment({id}) {
const { by, time, text, kids = [] } = useItemSubscription(id)
const [showComments, setShowComments] = useState(true)

return (
<div key={id}>
<div className="text">
{ text && text }
</div>
{
kids.length ? kids.map(id => <Comment id={id} />) : null
}
</div>
)
}

My Theory

export default function Item({match}) {
const id = match.params.id
const { title, by, url, score, time, text, kids = [], descendants} = useItemSubscription(id)
return (
<div>
<ItemHeader>
// ... omitted
</ItemHeader>
<ItemComments>
{
kids.length ?
kids.map(id => Comment({id})) : null
}
</ItemComments>
</div>
)
}

--

--

--

Javascript Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Block Scope and Shadowing in Js

Host your react-redux website with AWS S3

Javascript Iterators

Publish a Typescript React library to npm using TSdx

Does your React Native app SMELL ?

My face when I read a piece of code I wrote a year ago

Lessons I Learned from my First Four React Projects

Get “hooked” on these Redux hooks

The paper plane proof: our uplifting story of client-side JavaScript bucketing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jon Church

Jon Church

Javascript Developer

More from Medium

Using Keys in React

Integrating Your Frontend with Your Backend

How To Turn a String From a Form Into a Number in React

The most popular Javascript Library: ReactJs