freddy38510 / vue3-lazy-hydration

Lazy Hydration for Vue 3 SSR
MIT License
147 stars 6 forks source link

Why execute the function 'trackDepsOnRender'? #59

Open wangXiaoShow opened 1 year ago

wangXiaoShow commented 1 year ago

Hello, I've been learning your code lately, but I'm having some difficulties and I don't understand why the 'trackDepsOnRender' function is executed. I don't understand the comments of the code, and there doesn't seem to be a similar example of unit tests, can you give an example to explain why you do this, thanks ~

freddy38510 commented 1 year ago

Hello,

Initially the reactive effect function is setup to track dependencies when rendering the component. Since the render call is moved into an async callback to delay the hydration, the dependencies will not be tracked.

In simple terms this means that the lazily hydrated component will have no reactivity when finally hydrated.

https://github.com/freddy38510/vue3-lazy-hydration/blob/5a04bb5a76b9b3988fa81cfab8d4c35dab252cb6/src/composables/useLazyHydration.ts#L73&L78

https://github.com/vuejs/core/blob/160d5df34ae35c282fa48226842631584402d9fe/packages/runtime-core/src/renderer.ts#L1361&L1369

The trackDepsOnRender function re-run the reactive effect function when the render function is finally called. This is a trick to restore reactivity to the lazily hydrated component.

You can see it live through the demo, cloning the repository and running the dev script. Try commenting out the trackDepsOnRender function call, you will see that the counter component will not be reactive once hydrated.