import {useEffect, useRef} from '@wordpress/element'; const CodeMirrorEditor = ( {value, onChange, isActive} ) => { const textareaRef = useRef( null ); const editorRef = useRef( null ); const lastPushedValue = useRef( value ); const onChangeRef = useRef( onChange ); useEffect( () => { onChangeRef.current = onChange; }, [onChange] ); useEffect( () => { if ( textareaRef.current && !editorRef.current ) { const editor = wp.codeEditor.initialize( textareaRef.current, { /* ... settings ... */} ); editorRef.current = editor.codemirror; editorRef.current.setValue( value || '' ); editorRef.current.on( 'change', ( instance ) => { const content = instance.getValue(); lastPushedValue.current = content; onChangeRef.current( content ); } ); } }, [] ); useEffect( () => { if ( editorRef.current && isActive && value !== lastPushedValue.current ) { editorRef.current.setValue( value || '' ); lastPushedValue.current = value; } }, [value, isActive] ); useEffect( () => { if ( isActive && editorRef.current ) { editorRef.current.refresh(); } }, [isActive] ); return ; }; export default CodeMirrorEditor;