Skip to main content

Good Practices

Mutating the state based on its previous value

You don't want to use count.now() when referring to the previous value of your state when mutating it because depending on how you program your application, that value may be inaccurate, i.e. in asynchronous contexts.

The safest way to update your state based on its previous value is passing a function to .set(), where the first argument is the current value of your state and making its return to be the next value you want your state to be.

โŒ Don't:

const count = superstate(0)

count.set(count.now() + 1)

โœ… Do:

const count = superstate(0)

count.set((prev) => prev + 1)

Abstract complex logic with Extensions

It's tempting to just rush and use the built-in methods to handle your state. They work. However, it may become unsustainable at some point if you don't abstract complex, not obvious logic into small, organized pieces. Extensions are here for you.

โŒ Don't:

const user = superstate({
firstName: 'John',
lastName: 'Doe',
slug: 'john-doe',
})

user.set((prev) => ({
...prev,

firstName: 'Hello',
lastName: 'World',
slug: slugify('Hello World'),
}))

โœ… Do:

const user = {
state: superstate({ firstName: 'John', lastName: 'Doe', slug: 'john-doe' }),

rename({ firstName, lastName }) {
user.state.set(prev => {
...prev,

firstName,
lastName,
slug: slugify(`${firstName} ${lastName}`)
})
}
}

user.rename({ firstName: 'Hello', lastName: 'World' })
Types!

Extensions are seamlessly integrated with TypeScript. They show up in your editor's autocomplete as well as their arguments. Take advantage of it!

Keep your state serializable

Don't populate your superstates with non-serializable data, such as function, classes, etc. superstate expects its contents to be as agnostic as possible, so data can be handled in an unopinionated fashion. For example, localStorage persistency wouldn't be possible out of the box if data was not serializable. Learn more.

โŒ Don't:

const user = superstate({
firstName: 'John',
lastName: 'Doe',
slug: 'john-doe',
save() {
// Your save function.
},
})

โœ… Do:

const user = {
state: superstate({
firstName: 'John',
lastName: 'Doe',
slug: 'john-doe',
}),

save() {
// Your save function.
},
}