deno-musings/preactthing.tsx

44 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2024-10-11 13:04:47 -04:00
import { useState as preactUseState, useEffect as preactUseEffect } from 'preact/hooks';
import { useState as reactUseState, useEffect as reactUseEffect } from 'react';
import { options as preactOptions } from 'preact';
const isPreact = typeof preactUseState === 'function';
const useState = isPreact ? preactUseState : reactUseState;
const useEffect = isPreact ? preactUseEffect : reactUseEffect;
function useLogger(componentName) {
useEffect(() => {
console.log(`${isPreact ? 'Preact' : 'React'}: Component ${componentName} mounted`);
return () => {
console.log(`${isPreact ? 'Preact' : 'React'}: Component ${componentName} unmounted`);
};
}, [componentName]);
useEffect(() => {
console.log(`${isPreact ? 'Preact' : 'React'}: Component ${componentName} rendered`);
});
}
if (isPreact) {
preactOptions.__r = (vnode) => {
console.log('Preact: Rendering component:', vnode);
};
preactOptions.diffed = (vnode) => {
console.log('Preact: Component diffed:', vnode);
};
preactOptions.unmount = (vnode) => {
console.log('Preact: Unmounting component:', vnode);
};
}
// Example component using the custom hook
function MyComponent() {
useLogger('MyComponent');
return <div>My Component</div>;
}
export default MyComponent;