Docs
Getting started

Getting started

Installation

Using yarn

yarn add atomic-state

Or with npm

npm install --save atomic-state

Quick start

Example: A simple counter app

states.ts
import { create } from 'atomic-state'
 
const count = create({
  key: 'count',
  default: 0 // initial value
})
 
// export only what's needed
export const useCount = count.useValue
export const setCount = count.setValue
app.tsx
import { AtomicState } from 'atomic-state'
 
import { useCount, setCount } from '@/states'
 
function Counter() {
  const count = useCount()
 
  return (
    <div>
      <h2>Count: {count}</h2>
      <button
        onClick={() => {
          setCount(count + 1)
        }}
      >
        Increase
      </button>
    </div>
  )
}
 
export default function App() {
  // Remember to wrap with the AtomicState root
  return (
    <AtomicState>
      <Counter />
    </AtomicState>
  )
}

Suggestions

When creating an atom, it's a good idea to indicate it will contain some state by adding State after its friendly name. However, you are free to use any convention you want

In the example above, the count state is stored in the count atom:

import { create } from 'atomic-state'
 
const count = create({
  key: 'count',
  default: 0
})
 
// export only what's needed
export const useCount = count.useValue
export const setCount = count.setValue

You can rename it useCount and use it directly

import { create } from 'atomic-state'
 
export const useCount = create({
  key: 'count',
  default: 0
})
app.tsx
import { useCount } from '@/states'
 
export default function App() {
  const [count, setCount] = useCount()
 
  // etc
}
💡

It's recommended that you don't use - in the atom key, as it is used to differentiate stores internally

Last updated on August 8, 2024