useMount$()

Use useMount$() to execute code when the component is mounted into the rendering tree. (Another way to think about it is that useMount$() executes on component creation.)

Component Life Cycle and SSR

Qwik is resumable. Resumability means that the application starts up on the server and then the application is transferred to the client. On the client, the application continues execution from where it left off. The implication of this is that a component may be created on the server and destroyed on the client. This means that the component's useMount$() method may execute on the server and but its useCleanup$() method may execute on the client.

Usage of useMount$()

useMount$() is a hook that executes a callback when the component is mounted into the rendering tree. The useMount$() function can be async. useMount$() delays the rendering of the component until the useMount$() callback is finished executing. Typical usage for useMount$() is to fetch data needed for initial rendering.

useMount$() variations

The useMount$() hook is subdivided into server and client versions:

  • useServerMount$(): Hook that executes on the component mount when in a server environment. This is useful because server often has different APIs for retrieving data.

Use useMount$() if the code that needs to be executed is identical.

Server only imports

Because useServerMount$() hooks have $ in their name, they are subject to lazy loading. Lazy-loading means that the function is moved into a new file by the Optimizer. When the function is moved the Optimizer also moves any imports with it. This means that it is safe to have server-only imports as part of the useServerMount$() hook as they will be removed by the Optimizer.

Example

Use useServerMount() to fetch data needed for the rendering.

Edit Tutorial