Skip to main content


👻 Primitive and flexible state management for React
Go to Latest
---title: Atom creatorsnav: 8.02keywords: creators---
## atomWithToggle
> `atomWithToggle` creates a new atom with a boolean as initial state & a setter function to toggle it.This avoids the boilerplate of having to set up another atom just to update the state of the first.
```tsimport { WritableAtom, atom } from 'jotai'
export function atomWithToggle( initialValue?: boolean): WritableAtom<boolean, boolean | undefined> { const anAtom = atom(initialValue, (get, set, nextValue?: boolean) => { const update = nextValue ?? !get(anAtom) set(anAtom, update) }) return anAtom as WritableAtom<boolean, boolean | undefined>}```
An optional initial state can be provided as the first argument.
The setter function can have an optional argument to force a particular state, such as if you want to make a setActive function out of it.
Here is how it's used.
```jsimport { atomWithToggle } from 'XXX'
// will have an initial value set to trueconst isActiveAtom = atomWithToggle(true)```
And in a component:
```jsxconst Toggle = () => { const [isActive, toggle] = useAtom(isActiveAtom) return ( <> <button onClick={() => toggle()}> isActive: {isActive ? 'yes' : 'no'} </button> <button onClick={() => toggle(true)}>force true</button> <button onClick={() => toggle(false)}>force false</button> </> )}```
## atomWithToggleAndStorage
> `atomWithToggleAndStorage` is like `atomWithToggle` but also persist the state anytime it changes in given storage using [`atomWithStorage`](../utilities/storage.mdx).Here is the source:
```tsimport { WritableAtom, atom } from 'jotai'import { atomWithStorage } from 'jotai/utils'
export function atomWithToggleAndStorage( key: string, initialValue?: boolean, storage?: any): WritableAtom<boolean, boolean | undefined> { const anAtom = atomWithStorage(key, initialValue, storage) const derivedAtom = atom( (get) => get(anAtom), (get, set, nextValue?: boolean) => { const update = nextValue ?? !get(anAtom) set(anAtom, update) } ) return derivedAtom}```
And how it's used:
```jsimport { atomWithToggleAndStorage } from 'XXX'
// will have an initial value set to false & get stored in localStorage under the key "isActive"const isActiveAtom = atomWithToggleAndStorage('isActive')```
The usage in a component is also the same as `atomWithToggle`.
## atomWithCompare
> `atomWithCompare` creates atom that triggers updates when custom compare function `areEqual(prev, next)` is false.This can help you avoid unwanted re-renders by ignoring state changes that don't matter to your application.
Note: Jotai uses `` internally to compare values when changes occur. If `areEqual(a, b)` returns false, but `, b)` returns true, Jotai will not trigger an update.
```tsimport { atomWithReducer } from 'jotai/utils'
export function atomWithCompare<Value>( initialValue: Value, areEqual: (prev: Value, next: Value) => boolean) { return atomWithReducer(initialValue, (prev: Value, next: Value) => { if (areEqual(prev, next)) { return prev } return next })}```
Here's how you'd use it to make an atom that ignores updates that are shallow-equal:
```tsimport { atomWithCompare } from 'XXX'import { shallowEquals } from 'YYY'import { CSSProperties } from 'react'
const styleAtom = atomWithCompare<CSSProperties>( { backgroundColor: 'blue' }, shallowEquals)```
In a component:
```jsxconst StylePreview = () => { const [styles, setStyles] = useAtom(styleAtom) return ( <div> <div styles={styles}>Style preview</div> {/* Clicking this button twice will only trigger one render */} <button onClick={() => setStyles({ ...styles, backgroundColor: 'red' })}> Set background to red </button> {/* Clicking this button twice will only trigger one render */} <button onClick={() => setStyles({ ...styles, fontSize: 32 })}> Enlarge font </button> </div> )}```
## atomWithRefresh
> `atomWithRefresh` creates a derived atom that can be force-refreshed, by using> the update function.This is helpful when you need to refresh asynchronous data after performing aside effect.
It can also be used to implement "pull to refresh" functionality.
```tsimport { atom, Getter } from 'jotai'
export function atomWithRefresh<T>(fn: (get: Getter) => T) { const refreshCounter = atom(0) return atom( (get) => { get(refreshCounter) return fn(get) }, (_, set) => set(refreshCounter, (i) => i + 1) )}```
Here's how you'd use it to implement an refresh-able source of data:
```jsimport { atomWithRefresh } from 'XXX'
const postsAtom = atomWithRefresh((get) => fetch('').then((r) => r.json()))```
In a component:
```jsxconst PostsList = () => { const [posts, refreshPosts] = useAtom(postsAtom) return ( <div> <ul> { => ( <li key={}>{post.title}</li> ))} </ul> {/* Clicking this button will re-fetch the posts */} <button type="button" onClick={refreshPosts}> Refresh posts </button> </div> )}```
## atomWithRefreshAndDefault
> This is for an another implementation of [atomWithDefault](../utilities/resettable.mdx#atomwithdefault)### Look back to atomWithDefault behavior
As you can see in the example code in atomWithDefault section, the two atoms' relation is disconnected after updating created one, `count2Atom = atomWithDefault((get) => get(count1Atom) * 2)`. Let's confirm what's occurred,
- 1. Click "increment count1", then count1 is 2 and count2 is 4- 2. Click "increment count2", then count1 is 2 and count2 is 5 (Disconnected!!)Those atoms have no relation after updating count2Atom. So,
- Click "increment count1", count1 is incremented only- Even if you reset count2Atom, these dependency relation never come back### Motivation
In some cases,
- After disconnecting and resetting, they should come back to their relation- Derived atoms should be reset based on updated the original atom- We'd like to reset all derived atoms but just want to operate as simply as possibleHow do we make those cases?Here is a declarative way to create a function to provide a refreshable atom instead of atomWithDefault.
```jsconst refreshCountAtom = atom(0)
const baseDataAtom = atom(1) // original data, e.g. base count1Atomconst dataAtom = atom( (get) => { get(refreshCountAtom) // it's introduced at atomWithRefresh return get(baseDataAtom) }, (get, set, update) => { set(baseDataAtom, update) })
const atomWithRefreshAndDefault = (refreshAtom, getDefault) => { const overwrittenAtom = atom(null) return atom( (get) => { const lastState = get(overwrittenAtom) if (lastState && lastState.refresh === get(refreshAtom)) { return lastState.value } return getDefault(get) }, (get, set, update) => { set(overwrittenAtom, { refresh: get(refreshAtom), value: update }) } )}
// This is an alternative of `atomWithDefault((get) => get(count1Atom) * 2)`const refreshableAtom = atomWithRefreshAndDefault( refreshCountAtom, (get) => get(dataAtom) * 2)
// You can reset by updating just one atomconst resetRootAtom = atom(null, (get, set) => { set(refreshCountAtom, get(refreshCountAtom) + 1)})```
<CodeSandbox id="tcx2mk" />## atomWithListeners
> `atomWithListeners` creates an atom and a hook. The hook can be called to> add a new listener. The hook takes as an argument a callback, and that> callback is called every time the atom's value is set. The hook also> returns a function to remove the listener.This can be useful when you want to create a component that can listen to whenan atom's state changes without having to re-render that component with each ofthose state changes.
```tsimport { useEffect } from 'react'import { atom, useSetAtom, Getter, Setter, SetStateAction } from 'jotai'
type Callback<Value> = ( get: Getter, set: Setter, newVal: Value, prevVal: Value) => void
export function atomWithListeners<Value>(initialValue: Value) { const baseAtom = atom(initialValue) const listenersAtom = atom(<Callback<Value>[]>[]) const anAtom = atom( (get) => get(baseAtom), (get, set, arg: SetStateAction<Value>) => { const prevVal = get(baseAtom) set(baseAtom, arg) const newVal = get(baseAtom) get(listenersAtom).forEach((callback) => { callback(get, set, newVal, prevVal) }) } ) const useListener = (callback: Callback<Value>) => { const setListeners = useSetAtom(listenersAtom) useEffect(() => { setListeners((prev) => [...prev, callback]) return () => setListeners((prev) => { const index = prev.indexOf(callback) return [...prev.slice(0, index), ...prev.slice(index + 1)] }) }, [setListeners, callback]) } return [anAtom, useListener] as const}```
In a component:
```jsxconst [countAtom, useCountListener] = atomWithListeners(0)
function EvenCounter() { const [evenCount, setEvenCount] = useState(0) useCountListener( useCallback( (get, set, newVal, prevVal) => { // Every time `countAtom`'s value is set, we check if its new value // is even, and if it is, we increment `evenCount`. if (newVal % 2 === 0) { setEvenCount((c) => c + 1) } }, [setEvenCount] ) ) return <>Count was set to an even number {evenCount} times.</>}```
## atomWithBroadcast
> `atomWithBroadcast` creates an atom. The atom will be shared between> browser tabs and frames, similar to `atomWithStorage` but with the> initialization limitation.This can be useful when you want the state to interact with each other withoutthe use of localStorage and that by just using The Broadcast Channel API allowsbasic communication between browsing contexts (that is, windows, tabs, frames,create a component or iframes) and workers on the same origin. According to the MDN documentation receiving a message in initialization is not supported in broadcast and if we want to support that we may need to add extra stuff to atomWithBroadcast (like local storage).
```tsximport { atom } from 'jotai'
export function atomWithBroadcast<Value>(key: string, initialValue: Value) { const baseAtom = atom(initialValue) const listeners = new Set<(event: MessageEvent<any>) => void>() const channel = new BroadcastChannel(key) channel.onmessage = (event) => { listeners.forEach((l) => l(event)) } const broadcastAtom = atom<Value, { isEvent: boolean; value: Value }>( (get) => get(baseAtom), (get, set, update) => { set(baseAtom, update.value) if (!update.isEvent) { channel.postMessage(get(baseAtom)) } } ) broadcastAtom.onMount = (setAtom) => { const listener = (event: MessageEvent<any>) => { setAtom({ isEvent: true, value: }) } listeners.add(listener) return () => { listeners.delete(listener) } } const returnedAtom = atom<Value, Value>( (get) => get(broadcastAtom), (get, set, update) => { set(broadcastAtom, { isEvent: false, value: update }) } ) return returnedAtom}const broadAtom = atomWithBroadcast('count', 0)
const ListOfThings = () => { const [count, setCount] = useAtom(broadAtom) return ( <div> {count} <button onClick={() => setCount(count + 1)}>+1</button> </div> )}```
<CodeSandbox id="ugkzm0" />## atomWithDebounce
> `atomWithDebounce` helps with creating an atom where state set should be debounced.This util is useful for text search inputs, where you would like to call **functions in derived atoms only once** after waiting for a duration, instead of firing an action on every keystroke.
```tsximport { atom, SetStateAction } from 'jotai'
export default function atomWithDebounce<T>( initialValue: T, delayMilliseconds = 500, shouldDebounceOnReset = false) { const prevTimeoutAtom = atom<ReturnType<typeof setTimeout> | undefined>( undefined ) // DO NOT EXPORT currentValueAtom as using this atom to set state can cause // inconsistent state between currentValueAtom and debouncedValueAtom const _currentValueAtom = atom(initialValue) const isDebouncingAtom = atom(false) const debouncedValueAtom = atom( initialValue, (get, set, update: SetStateAction<T>) => { clearTimeout(get(prevTimeoutAtom)) const prevValue = get(_currentValueAtom) const nextValue = typeof update === 'function' ? (update as (prev: T) => T)(prevValue) : update const onDebounceStart = () => { set(_currentValueAtom, nextValue) set(isDebouncingAtom, true) } const onDebounceEnd = () => { set(debouncedValueAtom, nextValue) set(isDebouncingAtom, false) } onDebounceStart() if (!shouldDebounceOnReset && nextValue === initialValue) { onDebounceEnd() return } const nextTimeoutId = setTimeout(() => { onDebounceEnd() }, delayMilliseconds) // set previous timeout atom in case it needs to get cleared set(prevTimeoutAtom, nextTimeoutId) } ) // exported atom setter to clear timeout if needed const clearTimeoutAtom = atom(null, (get, set, _arg) => { clearTimeout(get(prevTimeoutAtom)) set(isDebouncingAtom, false) }) return { currentValueAtom: atom((get) => get(_currentValueAtom)), isDebouncingAtom, clearTimeoutAtom, debouncedValueAtom, }}```
### Caveat
Please note that this atom has different objectives from concurrent features in React 18 such as `useTransition` and `useDeferredValue` whose main aim is to prevent blocking of interaction with the page for expensive updates.
For more info, please read this github discussion under the section titled **"How is it different from setTimeout?"**
### Example Usage
The sandbox link below shows how we would use a derived atom to fetch state based on the value of `debouncedValueAtom`.
When typing a pokemon's name in `<SearchInput>`, we do not send a get request on every letter, but only after `delayMilliseconds` has passed since the last text input.
This reduces the number of backend requests to the server.
<CodeSandbox id="cjrz2y" />