# Atoms

Atom store can be used to store strings, numbers, arrays.

You can use it for objects too if you want to prohibit key changes and allow only replacing the whole object (like we do in [router](https://github.com/nanostores/router)).

To create it call `atom(initial)` and pass initial value as a first argument.

```ts
import { atom } from 'nanostores'

export const $counter = atom(0)
```

In TypeScript, you can optionally pass value type as type parameter.

```ts
export type LoadingStateValue = 'empty' | 'loading' | 'loaded'

export const $loadingState = atom<LoadingStateValue>('empty')
```

Then you can use `StoreValue<Store>` helper to get store’s value type in TypeScript:

```ts
import type { StoreValue } from 'nanostores'

type Value = StoreValue<typeof $loadingState> //=> LoadingStateValue
```

`store.get()` will return store’s current value. `store.set(nextValue)` will change value.

```ts
$counter.set($counter.get() + 1)
```

`store.subscribe(cb)` and `store.listen(cb)` can be used to subscribe for the changes in vanilla JS. For [React](/docs/frameworks/react-preact/)/[Vue](/docs/frameworks/vue/) we have extra special helpers `useStore` to re-render the component on any store changes.

Listener callbacks will receive the updated value as a first argument and the previous value as a second argument.

```ts
const unbindListener = $counter.subscribe((value, oldValue) => {
  console.log(`counter value changed from ${oldValue} to ${value}`)
})
```

`store.subscribe(cb)` in contrast with `store.listen(cb)` also call listeners immediately during the subscription. Note that the initial call for `store.subscribe(cb)` will not have any previous value and `oldValue` will be `undefined`.

See also [`effect()`](/docs/concepts/effects/) if you want to subscribe to multiple stores.

***

*Imported from the [Nano Stores README](https://github.com/nanostores/nanostores/blob/1.5.5/README.md#atoms) for version 1.5.5. Improve this page there.*
