JotaiJotai

状態
Primitive and flexible state management for React

Devtools

Install

Install jotai-devtools to your project to get started.

npm i jotai-devtools

Notes

  • <DevTools/> is optimized to be tree-shakable for production builds, and only works in a non-production environment
  • Hooks are dev-only, and are designed to work in a non-production environment
  • Feedback welcome, please file issues or ask questions on the Jotai DevTools GitHub Repo

UI DevTools

Enhance your development experience with the UI based Jotai DevTool.

Babel plugin setup - (Optional but highly recommended)

Use Jotai babel plugins for optimal debugging experience. Find the complete guide on the babel page and/or swc page.

Example:

{
"presets": [
// The preset includes two plugins:
// - jotai/babel/plugin-react-refresh to enable hot reaload for atoms
// - jotai/babel/plugin-debug-label to automatically adds debug labels to atoms
'jotai/babel/preset'
]
}

Example for Vite + React project:

// vite.config.ts
export default defineConfig({
plugins: [
react({
babel: {
presets: ['jotai/babel/preset'],
},
}),
],
})

Next JS setup

You may skip this section if you're not using Next.js.

Enable transpilePackages for the UI CSS and components to be transpiled correctly.

// next.config.ts
const nextConfig = {
// Learn more here - https://nextjs.org/docs/advanced-features/compiler#module-transpilation
// Required for UI css to be transpiled correctly 👇
transpilePackages: ['jotai-devtools'],
}
module.exports = nextConfig

Available props

type DevToolsProps = {
// defaults to false
isInitialOpen?: boolean
// pass a custom store
store?: Store
// Defaults to light
theme?: 'dark' | 'light'
// Set the position of the trigger button
// Defaults to `bottom-left`
position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'
// Custom nonce to allowlist jotai-devtools specific inline styles via CSP
nonce?: string
options?: {
// Private atoms are used internally in atom creators like `atomWithStorage`
// or `atomWithLocation`, etc. to manage the internal state.
// Defaults to `false`
shouldShowPrivateAtoms?: boolean
// Expands the JSON tree view on initial render on Atom Viewer tab, Timeline tab, etc.
// Defaults to `false`
shouldExpandJsonTreeViewInitially?: boolean
// The interval (in milliseconds) between each step of the time travel playback.
// Defaults to `750ms`
timeTravelPlaybackInterval?: number
// The maximum number of snapshots to keep in the history.
// The higher the number the more memory it will consume.
// Defaults to `Infinity`. Recommended: `~30`
snapshotHistoryLimit?: number
}
}

Usage

Provider-less

import { DevTools } from 'jotai-devtools'
import 'jotai-devtools/styles.css'
const App = () => {
return (
<>
<DevTools />
{/* your app */}
</>
)
}

With Provider

import { createStore } from 'jotai'
import { DevTools } from 'jotai-devtools'
import 'jotai-devtools/styles.css'
const customStore = createStore()
const App = () => {
return (
<Provider store={customStore}>
<DevTools store={customStore} />
{/* your app */}
</Provider>
)
}

Preview

useAtomsDebugValue

useAtomsDebugValue is a React hook that will show all atom values in React Devtools.

function useAtomsDebugValue(options?: {
store?: Store
enabled?: boolean
}): void

Internally, it uses useDebugValue which is only effective in DEV mode. It will catch all atoms that are accessible from the place the hook is located.

Example

import { useAtomsDebugValue } from 'jotai-devtools/utils'
const textAtom = atom('hello')
textAtom.debugLabel = 'textAtom'
const lenAtom = atom((get) => get(textAtom).length)
lenAtom.debugLabel = 'lenAtom'
const TextBox = () => {
const [text, setText] = useAtom(textAtom)
const [len] = useAtom(lenAtom)
return (
<span>
<input value={text} onChange={(e) => setText(e.target.value)} />({len})
</span>
)
}
const DebugAtoms = () => {
useAtomsDebugValue()
return null
}
const App = () => (
<Provider>
<DebugAtoms />
<TextBox />
</Provider>
)

useAtomDevtools

useAtomDevtools is a React hook that manages ReduxDevTools extension for a particular atom.

function useAtomDevtools<Value>(
anAtom: WritableAtom<Value, Value>,
options?: {
store?: Store
name?: string
enabled?: boolean
},
): void

The useAtomDevtools hook accepts a generic type parameter (mirroring the type stored in the atom). Additionally, the hook accepts two invocation parameters, anAtom and name. anAtom is the atom that will be attached to the devtools instance. name is an optional parameter that defines the debug label for the devtools instance. If name is undefined, atom.debugLabel will be used instead.

Example

import { useAtomDevtools } from 'jotai-devtools/utils'
// The interface for the type stored in the atom.
export interface Task {
label: string
complete: boolean
}
// The atom to debug.
export const tasksAtom = atom<Task[]>([])
// If the useAtomDevtools name parameter is undefined, this value will be used instead.
tasksAtom.debugLabel = 'Tasks'
export const useTasksDevtools = () => {
// The hook can be called simply by passing an atom for debugging.
useAtomDevtools(tasksAtom)
// Specify a custom type parameter
useAtomDevtools<Task[]>(tasksAtom)
// You can attach two devtools instances to the same atom and differentiate them with custom names.
useAtomDevtools(tasksAtom, 'Tasks (Instance 1)')
useAtomDevtools(tasksAtom, 'Tasks (Instance 2)')
}

useAtomsDevtools

⚠️ Note: This hook is experimental (feedbacks are welcome) and only works in a process.env.NODE_ENV !== 'production' environment.

useAtomsDevtools is a catch-all version of useAtomDevtools where it shows all atoms in the store instead of showing a specific one.

function useAtomsDevtools(
name: string,
options?: {
store?: Store
enabled?: boolean
},
): void

It takes a name parameter that is needed for naming the Redux devtools instance and a store parameter.

As a limitation for this API, we need to put useAtomsDevtools in a component where the consumed atoms should be in a lower place of the React tree than that component (AtomsDevtools in the below example). AtomsDevtools component can be considered as a best practice for our apps.

Example

const countAtom = atom(0);
const doubleCountAtom = atom((get) => get(countAtom) * 2);
function Counter() {
const [count, setCount] = useAtom(countAtom);
const [doubleCount] = useAtom(doubleCountAtom);
...
}
const AtomsDevtools = ({ children }) => {
useAtomsDevtools('demo')
return children
}
export default function App() {
return (
<AtomsDevtools>
<Counter />
</AtomsDevtools>
)
}

useAtomsSnapshot

⚠️ Note: This hook only works in a process.env.NODE_ENV !== 'production' environment. And it returns a static empty value in production.

useAtomsSnapshot takes a snapshot of the currently mounted atoms and their state.

function useAtomsSnapshot(options?: { store?: Store }): AtomsSnapshot

It accepts a store parameter and will return an AtomsSnapshot, which is basically a Map<AnyAtom, unknown>. You can use the Map API to iterate over atoms and their state. This hook is primarily meant for debugging and devtools use cases.

Be careful using this hook because it will cause the component to re-render for all state changes.

Example

import { Provider } from 'jotai'
import { useAtomsSnapshot } from 'jotai-devtools/utils'
const RegisteredAtoms = () => {
const atoms = useAtomsSnapshot()
return (
<div>
<p>Atom count: {atoms.size}</p>
<div>
{Array.from(atoms).map(([atom, atomValue]) => (
<p key={`${atom}`}>{`${atom.debugLabel}: ${atomValue}`}</p>
))}
</div>
</div>
)
}
const App = () => (
<Provider>
<RegisteredAtoms />
</Provider>
)

useGotoAtomsSnapshot

⚠️ Note: This hook only works in a process.env.NODE_ENV !== 'production' environment. And it works like an empty function in the production environment.

useGotoAtomsSnapshot will update the current Jotai state to match the passed snapshot.

function useGotoAtomsSnapshot(options?: {
store?: Store
}): (values: Iterable<readonly [AnyAtom, unknown]>) => void

This hook returns a callback, which takes a snapshot from the useAtomsSnapshot hook and will update the Jotai state. It accepts a store parameter. This hook is primarily meant for debugging and devtools use cases.

Example

import { Provider } from 'jotai'
import { useAtomsSnapshot, useGotoAtomsSnapshot } from 'jotai-devtools/utils'
const petAtom = atom('cat')
const colorAtom = atom('blue')
const UpdateSnapshot = () => {
const snapshot = useAtomsSnapshot()
const goToSnapshot = useGotoAtomsSnapshot()
return (
<button
onClick={() => {
const newSnapshot = new Map(snapshot)
newSnapshot.set(petAtom, 'dog')
newSnapshot.set(colorAtom, 'green')
goToSnapshot(newSnapshot)
}}
>
Go to snapshot
</button>
)
}