I am working on a project that creates a chrome extension. I am trying to return an object and I want to update it when curTab changed. However, I am getting an error: Rendered fewer hooks than expected. How can I fix that?
export const CategoryHandling = () => {
const tabHosts = useSelector((state: RootState) => state.tabHosts)
const curTab = useSelector((state: RootState) => state.currentTab)
const ns3Cache = useSelector((state: RootState) => state.ns3Cache)
const [ctgObject, setCategoryObject] = useState({
ads: [],
malware: [],
tracking: [],
family: [],
adult: [],
})
useEffect(() => {
setCategoryObject({
ads: [],
malware: [],
tracking: [],
family: [],
adult: [],
})
}, [curTab])
const hosts = curTab?.id ? tabHosts[curTab.id] : []
hosts &&
hosts.length !== 0 &&
hosts.map((host) => {
if (
ns3Cache?.[host] &&
ns3Cache?.[host].length !== 0 &&
!ns3Cache[host].hasOwnProperty('isLoading')
) {
ns3Cache[host].map((matchesItem) => {
if (
!ctgObject[matchesItem['list_category']].includes(
matchesItem['hostname']
)
) {
ctgObject[matchesItem['list_category']].push(
matchesItem['hostname']
)
}
})
}
})
return ctgObject
}
This is caused because of calling hooks inside iterations or conditional blocks, the more common scenarios in which I've found this kind of error happening were like:
// Using useSelector inside a map function
const myList = someIds.map((id) => useSelector((state) => state.someSlice[id]));
// Calling useEffect inside if block
if(someCondition) {
useEffect(() => {
// doing some stuff
}, []);
}
Look up for this kind of errors in your components.