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

Question

I’m creating a new block plugin, and I’m worried that it’s edit function is being called too many times. I’m not sure this is the right terminology, as I’m new to JavaScript, React, etc…, but, it seems that useState causes a re-render. If I just have a really simple edit:

import { useState } from 'WPBeginner - WordPress Tutorials/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 />;
}

then that console.log is getting hit twice per copy of the block on the post/page. I don’t want to over-optimize things, but, equally, I don’t know what this implies (is every script on the page getting re-executed twice?). Is this expected behavior for 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)?

0
philolegein 1 month 0 Answers 7 views 0

Leave an answer