Do I have to worry about useState causing a re-render?

admin

Administrator
Staff member
NB: I've asked this on wordpress.stackexchange, but it's not getting any response there, so trying here.
I'm not sure if this is WordPress specific, WordPress's overloaded React specific, or just React, but I'm creating a new block plugin for WordPress, and if I use
Code:
useState
in its
Code:
edit
function, the page is re-rendered, even if I never call the setter function.
Code:
import { useState } from '@wordpress/element';

export default function MyEdit( props ) {
        const {
                attributes: {
                    anAttribute
                },
                setAttributes,
        } = props;

        const [ isValidating, setIsValidating ] = useState( false );
        const post_id = wp.data.select("core/editor").getCurrentPostId();
        console.log('Post ID is ', post_id);

        const MyPlaceholder = () => {
            return(
                <div>this is a test</div>
            );
        };

        const Component = MyPlaceholder;

        return <Component />;
}
If I comment out
Code:
const [ isValidating, setIsValidating ] = useState( false );
then that
Code:
console.log
happens once. If I leave it in, it happens twice; even if I never check the value of
Code:
isValidating
, never mind calling
Code:
setIsValidating
. I don't want to over-optimize things, but, equally, if I use this block
Code:
n
times on a page, the page is getting rendered
Code:
2n
times. It's only on the admin side of things, because it's in the
Code:
edit
, so maybe not a big deal, but ... it doesn't seem right. Is this expected behavior for
Code:
useState
? Am I doing something wrong? Do I have to worry about it (from a speed perspective, from a potential race conditions as everything is re-rendered multiple times)?