Skip to main content

Your first superstate

It's time to have fun. Let's create a superstate that stores a number:

import { superstate } from '@superstate/core'

const count = superstate(0)

To display what count looks like:

console.log( // logs 0

And to change what count should be:


console.log( // logs 5

A more real-world example

const user = {
state: superstate({
firstName: 'John',
lastName: 'Doe',
role: 'user',
posts: []

rename: (firstName: string, lastName: string) => user.state.set({ firstName, lastName }),
promote: (newRole: Role) => user.state.set({ role: newRole }),
post: (newPost: Post) => user.state.set({ posts: [, newPost] }),

fullName: () => `${} ${}`,
isAdmin: () => === Role.Admin
getPostsAmount: () =>

enum Role {
Admin = 'admin',
Role = 'role'

interface User {
firstName: string
lastName: string
role: Role
posts: Post[]

interface Post {
id: string
title: string

TypeScript in often used in the examples, but it's not required. If you're using vanilla JavaScript, just ignore all the interfaces, enums, etc.

Now you can do things like:

user.rename('Jane', 'Doe')
user.promote(Role.Admin){ id: '1', title: 'Hello world' })

console.log(user.fullName()) // logs `Jane Doe`
console.log(user.isAdmin()) // logs `true`
console.log(user.getPostsAmount()) // logs `1`

And if you want to monitor when the state changes:

user.state.subscribe((state) => {
alert('Hey! The user state changed!')

If you want to do something inside a React component when the state changes, please read our React documentation.

Technical Overview

Under the hood, what superstate does is wrapping your state within a variable and enforcing queries and mutations to happen respectively through the .now() and .set() methods.

This allows superstate to keep track of what's going on with your state, and to keep your app posted about changes made to it as well.

An introductory video

You are a better learner when watching videos? Perhaps you'd like to know there's a commented version of the Notifications System example available as well. Check it out: