. Advertisement .
..3..
. Advertisement .
..4..
As the title says, I am getting the “rendered more hooks than during the previous render” error. How can I fix it so the error goes away? Here is my detail:
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const renderResults = () => {
return (
<section>
<p onClick={ setAllResultsVisible(!allResultsVisible) }>
More results v
</p>
{
allResultsVisible &&
<section className="entity-block--hidden-results">
...
</section>
}
</section>
);
};
return <div>{ renderResults() }</div>;
}
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const handleToggle = () => {
setAllResultsVisible(!allResultsVisible);
}
const renderResults = () => {
return (
<section>
<p onClick={ handleToggle }>
More results v
</p>
{
allResultsVisible &&
<section className="entity-block--hidden-results">
...
</section>
}
</section>
);
};
return <div>{ renderResults() }</div>;
}
When I operated it and I received the error text:
Uncaught Invariant Violation: Rendered more hooks than during the previous render.
I appreciate any help from you.
The cause: This error happens because of within the
onClick
as thesetAllResultsVisible
is called, it will trigger state change and result on every renderThe solution: Before
setAllResultsVisible
, you should change your onlick event add()=>
The same problem was faced by me. This is what I did:
The problem was that the component returned before the render was finished and the useEffect failed to run. The isLoading state was changed and the useEffect ran. I received an error message stating that the hook had been rendered more times than before.
It was a simple fix: