Uncaught Invariant Violation: Rendered more hooks than during the previous render

I faced the same issue. What I was doing was something like this:

const Table = (listings) => {

    const {isLoading} = useSelector(state => state.tableReducer);

    if(isLoading){
        return <h1>Loading...</h1>
    }

    useEffect(() => {
       console.log("Run something")
    }, [])

    return (<table>{listings}</table>)
}

I think what was happening was that on the first render, the component returned early and the useEffect didn’t run. When the isLoading state changed, the useEffect ran and I got the error – the hook rendered more times than the previous render.

A simple change fixed it:

const Table = (listings) => {
    
    const {isLoading} = useSelector(state => state.tableReducer);
        
    useEffect(() => {
        console.log("Run something")
    }, [])
    
    if(isLoading){
        return <h1>Loading...</h1>
    }
    return (<table>{listings}</table>)
}

Leave a Comment