Gutenberg Block constantly re-renders on state change in inner component
-
This is a simplified example:
const Test = () => { console.log("test called"); const [test, setTest] = React.useState('a'); const [test2, setTest2] = React.useState('b'); return <div> <form> <input value={test} onChange={(e)=>setTest(e.target.value)} /> <input value={test2} onChange={(e)=>setTest2(e.target.value)} /> </form> </div> } registerBlockType( 'activities/activity-gap-fill', { apiVersion: 2, title: 'Activity Gap Fill', icon: 'universal-access-alt', category: 'design', edit: ( { setAttributes, attributes } ) => { const blockProps = useBlockProps(); console.log("edit called", blockProps); return ( <div { ...blockProps }> <Test></Test> </div> ); }, save() { return null; }, } );
If I start typing in one of the form fields ‘test called’ is logged. This is expected. However – if the field loses focus then ‘edit called’ is logged. (NB. I don’t even have to start typing in the other field for ‘edit called’ to be logged – it is enough to just lose focus from the first field). Sometimes this just seems to happen randomly as well – even without the field losing focus.
This is code from a CodePen:
function Outer() { console.log("outer"); return <Inner></Inner> } function Inner() { const [test, setTest] = React.useState('a'); const [test2, setTest2] = React.useState('b'); console.log("inner"); return ( <div> <form> <input value={test} onChange={(e)=>setTest(e.target.value)} /> <input value={test2} onChange={(e)=>setTest2(e.target.value)} /> </form> </div> ); } ReactDOM.render(<Outer />, document.getElementById('app'));
As you can see it is basically the same. This behaves as expected – i can enter data into the two fields and swap between them and I only ever see ‘inner’ logged to the console.
It is something about the WordPress environment and this ‘edit’ function in a block which is causing this.
Does anyone know what is causing it – and how can I stop it? Or; is it just something I have to live with?
Thanks
- The topic ‘Gutenberg Block constantly re-renders on state change in inner component’ is closed to new replies.