# Observer pattern

In life, it is often necessary to be among the very first to learn about something happening. For example, a bell on YouTube allows you to receive an alert when a new video on your favorite channel is released, or when the operating system alerts you of an incoming update. And there are a lot of such examples. This task is so widespread that to solve it programmers introduced the **Observer** pattern. You do not need to think of a pattern as something complex and miraculous, for it is simply an approach to solving common problems.

Let us look at how the program understands when we need to report about a particular event and how it is related to the **Observer**. When you click on the bell on YouTube, you subscribe to the content-related changes on a specific channel. It is this word that lies at the root of this pattern. When you subscribe to a channel, you are being added to the list of subscribers who then will be notified about new videos. At the moment of adding a video the program will take a list of subscribers and send a notification to each of them.

In this example, the subscriber is the user, and the action performed is the sending of an alert. Still, if you look further, you can see that anyone can be a subscriber, and any function can be an action (in programming, such a function is called a callback). It means that with each change the component will call a callback to each of the subscribers.

A very good explanation of this pattern can be found at [refactoringGuru](https://refactoring.guru/ru/design-patterns/observer).

In `StartupJS`, every component has an `observer` wrapper. It is HOF (Higher Order Function) that adds reactivity to the component. This function is an observer that monitors changes in all values from the `FunctionalComponent` (see example below) associated with database, see [ShareDB](/docs/tutorial/ShareDBHooks) section. That is, a component wrapped in an `observer` reactively reacts to every change in the database. Thus, the information in `FunctionalComponent` is always up to date.

In general, it looks like this:

```jsx
observer(FunctionalComponent, options)
```

`options` can take the following values:
  - `forwardRef` if passed, then component wraps to `React.forwardRef`
  - `suspenseProps`:
    - `fallback` React component that is rendered while waiting for the component to load

```jsx
import {observer, useDoc} from 'startupjs'

export default observer(function User ({userId}) {
  const [user, $user] = useDoc('users', userId)
  return (
    <input value={user.name} onChange={e => $user.set('name', e.target.value)} />
  )
})
```
