import { useSyncExternalStore } from 'use-sync-external-store/shim'.../** * This component renders all of the editor's node views. */const Portals: React.FC<{ contentComponent: ContentComponent }> = ({ contentComponent,}) => { // For performance reasons, we render the node view portals on state changes only const renderers = useSyncExternalStore( contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot, ) // This allows us to directly render the portals without any additional wrapper return ( <> {Object.values(renderers)} </> )}
Pay attention to the comment in this above code snippet:
For performance reasons, we render the node view portals on state changes only
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'.../** * This hook allows you to watch for changes on the editor instance. * It will allow you to select a part of the editor state and re-render the component when it changes. * @example * ```tsx * const editor = useEditor({...options}) * const { currentSelection } = useEditorState({ * editor, * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }), * }) */export function useEditorState<TSelectorResult>( options: UseEditorStateOptions<TSelectorResult, Editor> | UseEditorStateOptions<TSelectorResult, Editor | null>,): TSelectorResult | null { const [editorStateManager] = useState(() => new EditorStateManager(options.editor)) // Using the `useSyncExternalStore` hook to sync the editor instance with the component state const selectedState = useSyncExternalStoreWithSelector( editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector as UseEditorStateOptions<TSelectorResult, Editor | null>['selector'], options.equalityFn ?? deepEqual, ) useIsomorphicLayoutEffect(() => { return editorStateManager.watch(options.editor) }, [options.editor, editorStateManager]) useDebugValue(selectedState) return selectedState}
Using the useSyncExternalStore hook to sync the editor instance with the component state
In the EditorContent.tsx, the import was from use-sync-external-store/shim but here in this useEditorState, import is from use-sync-external-store/shim/with-selector.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.