Uncaught Invariant Violation: Rendered more hooks than during the previous render : <p>I have a component that looks like this (very simplified version):</p>

<pre><code>const component = (props: PropTypes) =&gt; {

    const [allResultsVisible, setAllResultsVisible] = useState(false);

    const renderResults = () =&gt; {
        return (
            &lt;section&gt;
                &lt;p onClick={ setAllResultsVisible(!allResultsVisible) }&gt;
                    More results v
                &lt;/p&gt;
                {
                    allResultsVisible &amp;&amp;
                        &lt;section className="entity-block--hidden-results"&gt;
                            ...
                        &lt;/section&gt;
                }
            &lt;/section&gt;
        );
    };

    return &lt;div&gt;{ renderResults() }&lt;/div&gt;;
}
</code></pre>

<p>When I load the page this component is used on, I get this error: <code>Uncaught Invariant Violation: Rendered more hooks than during the previous render.</code> I tried to find an explanation of this error, but my searching returned no results. </p>

<p>When I modify the component slightly:</p>

<pre><code>const component = (props: PropTypes) =&gt; {

    const [allResultsVisible, setAllResultsVisible] = useState(false);

    const handleToggle = () =&gt; {
        setAllResultsVisible(!allResultsVisible);
    }

    const renderResults = () =&gt; {
        return (
            &lt;section&gt;
                &lt;p onClick={ handleToggle }&gt;
                    More results v
                &lt;/p&gt;
                {
                    allResultsVisible &amp;&amp;
                        &lt;section className="entity-block--hidden-results"&gt;
                            ...
                        &lt;/section&gt;
                }
            &lt;/section&gt;
        );
    };

    return &lt;div&gt;{ renderResults() }&lt;/div&gt;;
}
</code></pre>

<p>I no longer get that error. Is it because I included the <code>setState</code> function within the jsx that is returned by <code>renderResults</code>? It would be great to have an explanation of why the fix works.</p>
