useVisibleTask$()

Use useVisibleTask$() to execute code after the component is resumed. This is useful for setting up timers or streams on the client when the application is resumed.

track() and useVisibleTask$()

useVisibleTask$() receives a track() function just like useTask$(). Use the track() function to trigger the effect when the store is updated. See reactivity for more information.

Component Life Cycle and SSR

Qwik is resumable. Resumability means that the application starts on the server and then is transferred to the client. On the client, the application continues execution from where it left off. A common use case is creating a component on the server, pausing, and then resuming on the client. To make the component fully functional, it may be necessary to execute code eagerly on the client to set up timers or streams.

useVisibleTask$() is a client-only method. (There is no equivalent on the server.)

NOTE See useTask$() for behavior that needs to be executed on both client and server.

When is useVisibleTask$() executed?

Client effect code is executed after the component is resumed. The useVisibleTask$() method takes an additional argument ({strategy:'intersection-observer|document-ready|document-idle'}) that controls when the effect is executed. There are three options:

  • intersection-observer (default): the task will first execute when the element is visible in the viewport, under the hood it uses the IntersectionObserver API.
  • document-ready: the task will first execute when the document is ready, under the hood it uses the document load event.
  • document-idle: the task will first execute when the document is idle, under the hood it uses the requestIdleCallback API.

Example

The example shows a clock component that is rendered below the fold. Use the useVisibleTask$() to make the clock update the current time every second to make it work on the client. We have provided the utility function updateClock to aid your implementation.

Keep in mind that useVisibleTask$() should return a cleanup function that releases the setInterval timer so that the timer can be properly cleaned up when the component is unmounted/destroyed.

Edit Tutorial