Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HMR without JSX triggers useEffect hook outside changed context #565

Closed
Siilwyn opened this issue Feb 6, 2025 · 1 comment
Closed

HMR without JSX triggers useEffect hook outside changed context #565

Siilwyn opened this issue Feb 6, 2025 · 1 comment

Comments

@Siilwyn
Copy link
Contributor

Siilwyn commented Feb 6, 2025

👋 hi it's me again, sorry!

Using Preact with @preact/preset-vite and no JSX I found out that on HMR effects are triggered when anything changes.

For example with this Counter component:

import { h } from 'preact';
import { signal, computed } from '@preact/signals';
import { useEffect } from 'preact/hooks';

const count = signal(0);
const double = computed(() => count.value * 2);

export default function Counter() {
  useEffect(() => {
    console.log('greeetings');
  }, []);

  return (
    h(
      'button',
      { onClick: () => count.value++ },
      `${count} x 2 = ${double}`
    )
  );
}

When used by a JSX file, test-app.jsx:

import { h } from 'preact';
import Counter from './components/Counter.mjs';

export default function TestApp() {
  return (
    <div>
      hi
      <Counter />
    </div>
  );
}

Change hi in the app component will not cause the effect and thus log to be fired.

However when used by a JS file, test-app.mjs:

import { h } from 'preact';
import Counter from './components/Counter.mjs';

export default function TestApp() {
  return h(
    'div',
    {},
    [
      'hii',
      Counter(),
    ]
  )
}

Changing hi will cause Counter to run the effect again, interestingly the state is kept so count doesn't change.

I'm probably missing something here but I can't quite put my finger on it.

@Siilwyn
Copy link
Contributor Author

Siilwyn commented Feb 6, 2025

Just as I'm posting this I remember I'm not wrapping the component as a VNode. 😅

h(Counter) does the trick...

@Siilwyn Siilwyn closed this as completed Feb 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant