Senior
How to memoize a static JSX block inside a component without extracting it into a separate component? What dependency array is needed?
sobes.tech AI
Answer from AI
To memoize a static JSX block inside a component without extracting it into a separate component, you can use the useMemo hook from React.
Example:
import React, { useMemo } from 'react';
function MyComponent() {
const staticBlock = useMemo(() => (
<div>
<h1>Static Header</h1>
<p>This block does not depend on props or state.</p>
</div>
), []); // Empty dependencies array
return (
<div>
{staticBlock}
{/* Other JSX */}
</div>
);
}
Here, the dependencies array is empty ([]) because the block is static and does not depend on external data. This guarantees that the JSX block will be computed once when the component mounts and will not be recreated on re-render.