How to fix React Error: Rendered fewer hooks than expected

Jon Church
Nov 22, 2018 · 4 min read
Photo by FuYong Hua on Unsplash

TLDR;


// don't use hooks within a conditional statement!export default function ListView({history, match}) {
const filter = match.params.filter
let [items, maxPages] = useTopStories(filter, page)
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>
)
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade