Skip to main content

Memo Directive

This directive memoizes a component with React.memo to avoid unnecessary rerenders.

const memoMap = new Map();

function memoMiddleware(next, type, { $memo, ...props }, key) {
if ($memo && typeof type === 'function') {
let memoed = memoMap.get(type);
if (!memoed) {
memoed = React.memo(type);
memoMap.set(type, memoed);
}

return next(memoed, props, key);
}

return next(type, props, key);
}

addMiddlewares(memoMiddleware);

Usage

function App() {
// ...
return (
<div>
<Memoed>This is not memoed.</Memoed>
<Memoed $memo>This is memoed.</Memoed>
</div>
);
}
http://localhost:3000

Timer: 0

This is not memoed. Render count: 1

This is memoed. Render count: 1

Typescript types

declare module 'react' {
interface Attributes {
$memo?: boolean;
}
}