alewin/useWorker

Why on each call to the worker the dependencies are re-fetched?

JonatanSalas opened this issue ยท 12 comments

Hi! First of all thanks for this awesome library!

I would like to ask something that I don't clearly understand. It's related to how the useWorker manages external dependencies.

I clearly don't understand why, but, when I make a recall to the function given from the useWorker hook, for some reason it re-calls o re-imports the dependencies array.

This behavior is also present in the external scripts example: https://icji4.csb.app/external

If you open the network inspector, you can see when you click the button for Sorting Dates.

Here you can see:

Captura de Pantalla 2020-04-11 a la(s) 14 57 05

What I would like to understand is that if this behavior is expected from the library and why? In case that not, I would submit a PR to fix this!

Anyway, thanks again for your library!

Thanks for reporting @JonatanSalas, this is a serious problem...
I opened a PR with a possible solution, tomorrow I'll prepare a release candidate

Hi @JonatanSalas can you try the @next build with the bugfix?

Install

npm install @koale/useworker@next ( or yarn )

package.json

"@koale/useworker": "^3.0.0-beta"

@alewin I'm on it!

Great! Let me know

@alewin I've updated to the v3.0.0-beta but I can see still the refetch behavior.

Captura de Pantalla 2020-04-13 a la(s) 21 04 26

I will check anyway if I've to optimize something from my component.

Ok, I have now seen your code:
https://github.com/BlackBoxVision/react-qr-reader/blob/e48a2326f6ecb069dbcefb44a67ac92c8af21f65/src/QrReader/hooks/useQrReader.ts#L107
It's called in a loop and since the worker after finishing is killed (to save memory), the dependency is loaded several times, but perhaps there is a possible solution which I am working on.
I will keep you updated :)

Thank you @alewin! If you need anything just let me know.

Good news!! ๐ŸŽ‰I found a non-invasive solution, passing an additional parameter to prevent the worker from being "killed" each time.

Hi @JonatanSalas can you try the @next build with the bugfix?

Install

npm install @koale/useworker@next

Snippet

  const [decodeQrImage, _, clearWorker] = useWorker(decodeQR, {
    dependencies: ['https://cdn.jsdelivr.net/npm/jsqr@1.2.0/dist/jsQR.min.js'],
    autoTerminate: false,
  });

setting autoTerminate: false the worker stays alive until the clearWorker function is called.


I suggest you kill the worker on component unmount, when autoTerminate is false:

useEffect(() => () => clearWorker(), [])

@alewin I'll be trying it today and letting you know. Thank you very much for your work!

Hey @JonatanSalas any news? :)

@alewin I've adjusted the code to use the latest version of your lib + autoTerminate prop. The component is working pretty neat now and only downloading the external script for once.

Thank you very much for this awesome library