API
globalState
Creates a global state that can optionally be persistent.
src/stores/example.ts
import { globalState } from '@codeleap/store'
export const state = globalState(value, config)
Parameters
value: The initial state value.config(GlobalStateConfig): Optional configuration.persistKey(string | null): If defined, it activates the persistence of the state.
Methods
The globalState is an
atomthat can be modified, so it includes all the methods described in nanostores
use: React hook for consuming the global state. You can pass a selector to extract a specific value, which is useful for object states to avoid unnecessary re-renders:
src/stores/example.tsx
import { globalState } from '@codeleap/store'
const state = globalState({ value: 1, value2: 2 })
function Component() {
  const value1 = state.use(state => state.value)
  // re-renders if value1 changes and never if value2 changes
  return null
}
function Component2() {
  const values = state.use()
  // re-renders if value1 or value2 changes
  return null
}
set: Updates the global state immutably.
src/stores/example.tsx
const count = globalState(1)
count.set(2)
get: Retrieves the global state.
src/stores/example.tsx
const count = globalState(1)
const value = count.get()
value: Accesses the current value of the global state.
src/stores/example.tsx
const count = globalState(1)
const value = count.value
Array
If the state value is an array, you will have access to the default array methods for manipulation, in addition to the ones provided above.