Skip to content

Commit

Permalink
perf: memoize TDocumentRenderer to prevent rendering from ascendents
Browse files Browse the repository at this point in the history
  • Loading branch information
jsamr committed Jun 4, 2021
1 parent 087073f commit 2ec060b
Showing 1 changed file with 50 additions and 48 deletions.
98 changes: 50 additions & 48 deletions packages/render-html/src/TDocumentRenderer.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,57 @@
import React, { useEffect, useMemo } from 'react';
import React, { memo, useEffect, useMemo } from 'react';
import { TDocument } from '@native-html/transient-render-engine';
import { DocumentMetadata, RenderHTMLFragmentProps } from './shared-types';
import DocumentMetadataProvider from './context/DocumentMetadataProvider';
import { useTNodeChildrenRenderer } from './context/TChildrenRendererContext';
import { defaultMarkers } from './helpers/getMarkersFromTNode';

const TDocumentRenderer = ({
tdoc,
baseUrl,
onDocumentMetadataLoaded
}: {
tdoc: TDocument;
baseUrl?: string;
onDocumentMetadataLoaded?: RenderHTMLFragmentProps['onDocumentMetadataLoaded'];
}) => {
const TNodeChildrenRenderer = useTNodeChildrenRenderer();
const metadata: DocumentMetadata = useMemo(() => {
const {
baseHref,
baseTarget,
lang,
links,
meta,
title,
dir
} = tdoc.context;
return {
baseTarget,
baseUrl: baseUrl ?? baseHref,
lang,
dir,
links,
meta,
title
};
}, [tdoc.context, baseUrl]);
useEffect(() => {
onDocumentMetadataLoaded?.call(null, metadata);
}, [onDocumentMetadataLoaded, metadata]);
const parentMarkers = useMemo(
() => ({
...defaultMarkers,
direction: metadata.dir,
lang: metadata.lang
}),
[metadata.dir, metadata.lang]
);
return (
<DocumentMetadataProvider value={metadata}>
<TNodeChildrenRenderer parentMarkers={parentMarkers} tnode={tdoc} />
</DocumentMetadataProvider>
);
};
const TDocumentRenderer = memo(
({
tdoc,
baseUrl,
onDocumentMetadataLoaded
}: {
tdoc: TDocument;
baseUrl?: string;
onDocumentMetadataLoaded?: RenderHTMLFragmentProps['onDocumentMetadataLoaded'];
}) => {
const TNodeChildrenRenderer = useTNodeChildrenRenderer();
const metadata: DocumentMetadata = useMemo(() => {
const {
baseHref,
baseTarget,
lang,
links,
meta,
title,
dir
} = tdoc.context;
return {
baseTarget,
baseUrl: baseUrl ?? baseHref,
lang,
dir,
links,
meta,
title
};
}, [tdoc.context, baseUrl]);
useEffect(() => {
onDocumentMetadataLoaded?.call(null, metadata);
}, [onDocumentMetadataLoaded, metadata]);
const parentMarkers = useMemo(
() => ({
...defaultMarkers,
direction: metadata.dir,
lang: metadata.lang
}),
[metadata.dir, metadata.lang]
);
return (
<DocumentMetadataProvider value={metadata}>
<TNodeChildrenRenderer parentMarkers={parentMarkers} tnode={tdoc} />
</DocumentMetadataProvider>
);
}
);
export default TDocumentRenderer;

0 comments on commit 2ec060b

Please sign in to comment.