Memo Directive
This directive memoizes a component with React.memo to avoid unnecessary rerenders.
const memoMap = new Map();
function memoMiddleware(next, type, props, key) {
if (!('$memo' in props)) return next(type, props, key);
const { $memo, ...rest } = props;
if ($memo && typeof type === 'function') {
let memoed = memoMap.get(type);
if (!memoed) {
memoed = React.memo(type);
memoMap.set(type, memoed);
}
return next(memoed, rest, key);
}
return next(type, rest, 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;
}
}