Preact: 10.0.0-alpha.0 - Hook useEffect never gets called

Created on 5 Mar 2019  路  7Comments  路  Source: preactjs/preact

When using a code like this in 10.0.0-alpha.0:

import { useEffect } from 'preact/hooks';

function Component(props) {
    useEffect(() => {
        console.log('effect');
    });

    return <div> test </div>;
}

The console log never gets called. I'm having a hard time getting preact functional components to work in codesandbox or I'd have posted a repro, sorry about that.

bug important

Most helpful comment

Can confirm, just tried it out with the code in master and the issue is fixed there 馃帀

All 7 comments

My first guess is that afterPaint is not correctly patched here https://github.com/developit/preact/blob/2a8ad14756ed570af7db6163ed16b1f627a3fcdd/hooks/src/index.js#L196-L199

In addition to the above issue, a related issue regarding the execution order of useEffect and useLayoutEffect seems to be inconsistent to react too.

const App = () => {
  useEffect(() => {
    console.log('useEffect');
  });
  useLayoutEffect(() => {
    console.log('useLayoutEffect');
  });
  return <div>Hello World!</div>;
};

After the initial render, the re-render should print useLayoutEffect then useEffect in react. But in alpha.0 it would print useEffect first then useLayoutEffect.

Not sure how much are they related? If the maintainers would prefer to open another issue then I'm happy to do so too 馃檪.

Just an FYI

i can get useEffect to trigger when doing this, though its not a good solution :P

image

Seem it just wont trigger on initial render, but does trigger when it re-renders, and because i have no inputs ( [] ) it only runs once (which is what i want).

Edit: Final remark calling setTime("trigger") with out timeout doesnt seem to trigger useEffect this might because calling setState ( setTime ) in initial render doesnt trigger another render .... might be a bug ??

Have encountered similar to the above, and mirror the sentiments of @timpur, seems like the initial useState callback doesn't trigger a render in a similar way to that of react. The setTimeout hack seems to fix the issue for now.

For context I am exploring using microstates with PreactX by using this https://codesandbox.io/s/github/microstates/todomvc/tree/master/sandboxes/react as a starting point. But the combination of their useType wrapper around useState paired with useEffect was giving inconsistent results.

For those wanting a quick hack to be able to use useEffect until this is fixed, from @timpur just add these two lines within your functional component:

const [hack, setHack] = useState(0)
if (!hack) setTimeout(() => setHack(1), 0)

I think this might be fixed in master. I was seeing similar behavior and submitted #1320 to fix my issue. Hopefully it fixes this one.

Can confirm, just tried it out with the code in master and the issue is fixed there 馃帀

Was this page helpful?
0 / 5 - 0 ratings