Skip to content

Commit

Permalink
Completely get rid of useEffect in Frame component
Browse files Browse the repository at this point in the history
  • Loading branch information
tomas-c committed May 16, 2024
1 parent 81b90d4 commit e4c6692
Showing 1 changed file with 17 additions and 30 deletions.
47 changes: 17 additions & 30 deletions packages/core/src/render/Frame.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { deprecationWarning, ROOT_NODE } from '@craftjs/utils';
import React, { useEffect, useRef } from 'react';
import React, { useRef } from 'react';

import { useInternalEditor } from '../editor/useInternalEditor';
import { SerializedNodes } from '../interfaces';
Expand Down Expand Up @@ -39,41 +39,28 @@ export const Frame: React.FC<React.PropsWithChildren<FrameProps>> = ({
});
}

const initialState = useRef({
initialChildren: children,
initialData: data || json,
});
const isLoaded = useRef(false);

const isInitialLoadedRef = useRef(false);
if (!isLoaded.current) {
const initialData = data || json;

if (!isInitialLoadedRef.current && initialState.current.initialData) {
actions.history.ignore().deserialize(initialState.current.initialData);
isInitialLoadedRef.current = true;
}

useEffect(() => {
const { initialChildren } = initialState.current;
if (initialData) {
actions.history.ignore().deserialize(initialData);
} else {
const rootNode = React.Children.only(children) as React.ReactElement;

// Prevent recreating Nodes from child elements if we already did it the first time
// Usually an issue in React Strict Mode where this hook is called twice which results in orphaned Nodes
const isInitialLoaded = isInitialLoadedRef.current;
const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
if (jsx === rootNode) {
node.id = ROOT_NODE;
}
return node;
});

if (!initialChildren || isInitialLoaded) {
return;
actions.history.ignore().addNodeTree(node);
}

const rootNode = React.Children.only(initialChildren) as React.ReactElement;

const node = query.parseReactElement(rootNode).toNodeTree((node, jsx) => {
if (jsx === rootNode) {
node.id = ROOT_NODE;
}
return node;
});

actions.history.ignore().addNodeTree(node);
isInitialLoadedRef.current = true;
}, [actions, query]);
isLoaded.current = true;
}

return <RenderRootNode />;
};

0 comments on commit e4c6692

Please sign in to comment.