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


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 'wordpress user/element';

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

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

        const MyPlaceholder = () => {
                <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)?

philolegein 2 years 2020-12-16T00:10:23-05:00 0 Answers 7 views 0

Leave an answer