---
title: 'Agents'
description: "Yew's Actor System"
---

import useBaseUrl from '@docusaurus/useBaseUrl'
import ThemedImage from '@theme/ThemedImage'

Agents are a way to offload tasks to web workers.

In order for agents to run concurrently, Yew uses
[web-workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers).

## Lifecycle

<!--
The diagram is produced with nomnoml (nomnoml.com),
The code can be found in the <desc> tag of the svgs.
-->

<ThemedImage
    alt="agent lifecycle diagram"
    sources={{
        light: useBaseUrl('/img/agent-lifecycle-light.svg'),
        dark: useBaseUrl('/img/agent-lifecycle-dark.svg'),
    }}
/>

## Types of Agents

### Reaches

-   Public - There will exist at most one instance of a Public Agent at any given time. Bridges will
    spawn or connect to an already spawned agent in a web worker.
    When no bridges are connected to this agent, the agent will disappear.

-   Private - Spawn a new agent in a web worker for every new bridge. This is good for moving shared but
    independent behavior that communicates with the browser out of components. When
    the connected bridge is dropped, the agent will disappear.

-   Global \(WIP\)

## Communication between Agents and Components

### Bridges

A bridge allows bi-directional communication between an agent and a component. Bridges also allow agents to communicate with one another.

A `use_bridge` hook is also provided to create bridges in a function component.

### Dispatchers

A dispatcher allows uni-directional communication between a component and an agent. A dispatcher allows a component to send messages to an agent.

## Overhead

Agents use web workers \(i.e. Private and Public\). They incur a serialization overhead on the
messages they send and receive. Agents use [bincode](https://github.com/servo/bincode) to communicate
with other threads, so the cost is substantially higher than just calling a function.

## Further reading

-   The [web_worker_fib](https://github.com/yewstack/yew/tree/yew-v0.20.0/examples/web_worker_fib) example shows how
    components can send message to and receive message from agents.
