Back to Nuxt

useState

docs/4.api/2.composables/use-state.md

4.4.42.1 KB
Original Source

Usage

ts
// Create a reactive state and set default value
const count = useState('counter', () => Math.round(Math.random() * 100))

:read-more{to="/docs/4.x/getting-started/state-management"}

::important Because the data inside useState will be serialized to JSON, it is important that it does not contain anything that cannot be serialized, such as classes, functions or symbols. ::

::warning useState is a reserved function name transformed by the compiler, so you should not name your own function useState. ::

:video-accordion{title="Watch a video from Alexander Lichter about why and when to use useState" videoId="mv0WcBABcIk"}

Using shallowRef

If you don't need your state to be deeply reactive, you can combine useState with shallowRef. This can improve performance when your state contains large objects and arrays.

ts
const state = useState('my-shallow-state', () => shallowRef({ deep: 'not reactive' }))
// isShallow(state) === true

Type

ts
export function useState<T> (init?: () => T | Ref<T>): Ref<T>
export function useState<T> (key: string, init?: () => T | Ref<T>): Ref<T>
  • key: A unique key ensuring that data fetching is properly de-duplicated across requests. If you do not provide a key, then a key that is unique to the file and line number of the instance of useState will be generated for you.
  • init: A function that provides initial value for the state when not initiated. This function can also return a Ref.
  • T: (typescript only) Specify the type of state

Troubleshooting

Cannot stringify arbitrary non-POJOs

This error occurs when you try to store a non-serializable payload with useState, such as class instances.

If you want to store class instances with useState that are not supported by Nuxt, you can use definePayloadPlugin to add a custom serializer and deserializer for your classes.

:read-more{to="/docs/4.x/api/composables/use-nuxt-app#payload"}